1059 Prime Factors (25point(s))
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1 × p2k2 x … x pmkm.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N =
p1^
k1*
p2^
k2*
…*
pm^
km, where pi’s are prime factors of N in increasing order, and the exponent ki is the number of pi – hence when there is only one pi, ki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^211171011291
題目大意:
給一個整數 N,從小到大輸出該數的質因子
設計思路:
建立一個素數表,遍歷素數表,查找質因子
- INT 最大值爲 2147483647,開根號得 46340.95,素數表大小 5 萬左右
- 所以不能被 5 萬以內整除的數一定是素數
- 當最後 N > 1 時,state 是爲了標示是否輸出過因子,例如 30027 = 3 * 10009,最後輸出 10009 前面要有 * 號
編譯器:C (gcc)
#include<stdio.h>
#define MAX 46342
//INT 2147483647 46340.95
int main(void) {
int prime[MAX] = {-1, -1};
int i, j;
for (i = 2; i * i < MAX; i++) {
for (j = 2; i * j < MAX; j++) {
prime[i * j] = -1;
}
}
int n;
scanf("%d", &n);
printf("%d=", n);
if (n == 1) {
printf("1");
}
int state = 0;
for (i = 2; i < MAX && n >= 2; i++) {
int count = 0, flag = 0;
while (prime[i] == 0 && n % i == 0) {
count++;
n /= i;
flag = 1;
}
if (flag) {
if (state) {
printf("*");
}
printf("%d", i);
state = 1;
}
if (count > 1) {
printf("^%d", count);
}
}
if (n > 1) {
printf("%s%d", state ? "*": "", n);
}
return 0;
}