整数分解(Integer factorization)又叫质因数分解(质因子分解)是指把一个正整数写成几个素数的乘积。
最简单的算法是,从2到N进行试除,能整除的时候就说明找到了一个新的因子,而这个过程中由于是从较小的数開始除起所以必然会先找到能整除的最小的素数。
#include <stdio.h> void pd(int num) { int i; for (i = 2; i <= num; i++) if (!(num % i)) { pd(num / i); if (num != i) printf("*"); printf("%d", i); break; } } int main(int argc, const char *argv[]) { int num; scanf("%d", &num); printf("%d=", num); pd(num); printf("/n"); return 0; }
也能够用非递归的方法:
#include <stdio.h> void pd(int num) { int i; while(num > 1) { int flag = 0; for (i = 2; i <= num; i++) { if (!(num % i)) { flag = 1; num /= i; printf("%d", i); break; } } if (!flag) return; if (num > 1) printf("*"); } } int main(int argc, const char *argv[]) { int num; scanf("%d", &num); printf("%d=", num); pd(num); printf("/n"); return 0; }
最后是筛法,首先通过筛法将2到N中全部的合数排除,单独找出素数,分解时直接在素数表中用这些素数试除,就能够加快分解的速度:
#include <stdio.h> #include <stdlib.h> #include <memory.h> #include <math.h> #define N 1024 int *makePrimeList(int max, int *prime_count) { int i, j; int *table = (int *)malloc(sizeof(int) * (max + 1)); memset(table, 0, sizeof(int) * (max + 1)); for (i = 2; i <= (int)sqrt(max); i++) { for (j = i + i; j <= max; j += i) { *(table + j) = 1; } } *prime_count = 0; for (i = 2; i <= max; i++) if (!(*(table + i))) (*prime_count)++; int *lst = (int*)malloc(sizeof(int) * (*prime_count)); int *lst_p = lst; for (i = 2; i <= max; i++) if (!(*(table + i))) *lst_p++ = i; free(table); return lst; } void pd(int num, int *prime_lst, int prime_count) { int *prime_lst_endp = prime_lst + prime_count; while(num > 1) { int flag = 0; int *prime_lst_p = prime_lst; while (prime_lst_p != prime_lst_endp) { if (!(num % *prime_lst_p)) { flag = 1; num /= *prime_lst_p; printf("%d", *prime_lst_p); break; } prime_lst_p++; } if (!flag) return; if (num > 1) printf("*"); } } int main(int argc, const char *argv[]) { int num; int prime_count; scanf("%d", &num); int *prime_lst = makePrimeList(N, &prime_count); printf("%d=", num); pd(num, prime_lst, prime_count); printf("/n"); free(prime_lst); return 0; }