標籤:pat zju
題目連結:http://pat.zju.edu.cn/contests/ds/2-07
給定某個正整數N,求其素因子分解結果,即給出其因式分解運算式 N = p1^k1 * p2^k2 *…*pm ^km。
輸入格式說明:
輸入long int範圍內的正整數N。
輸出格式說明:
按給定格式輸出N的素因式分解運算式,即 N = p1^k1 * p2^k2 *…*pm ^km,其中pi為素因子並要求由小到大輸出,指數ki為pi的個數;當ki==1即因子pi只有一個時不輸出ki。
範例輸入與輸出:
| 序號 |
輸入 |
輸出 |
| 1 |
1024 |
1024=2^10 |
| 2 |
1323 |
1323=3^3*7^2 |
| 3 |
97532468 |
97532468=2^2*11*17*101*1291 |
| 4 |
1 |
1=1 |
| 5 |
3 |
3=3 |
代碼如下:
#include <cstdio>#include <cstring>#include <cmath>#define LL intconst int MAXN = 11117;int main(){ LL n; int p[MAXN], k[MAXN]; while(~scanf("%d",&n)) { LL tt = n; memset(p,0,sizeof(p)); memset(k,0,sizeof(k)); int i = 2; int cont = 0; int flag = 0; int l = 0; if(n == 1) { printf("1=1\n"); continue; } while(n!=1) { while(n%i==0) { flag = 1; cont++; n /= i; } if(flag) { p[l] = i; k[l] = cont; l++; flag = 0; cont = 0; } i++; } printf("%d=",tt); for(int i = 0; i < l-1; i++) { if(k[i] == 1) printf("%d*",p[i]); else printf("%d^%d*",p[i],k[i]); } if(k[l-1] == 1) printf("%d\n",p[l-1]); else printf("%d^%d\n",p[l-1],k[l-1]); } return 0;}
2-07. 素因子分解(20) (ZJUPAT 數學)