筛素数法,分解因式
// 1059_Prime_Factors.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <math.h> const int N = 31650; bool prime[N]; void selectPrime(){ prime[0] = prime[1] = true; for(int i = 2; i < N; i++){ if(!prime[i]){ for(int j = i * i; j < N; j += i){ prime[j] = true; } } } } void countYue(int num){ int tNum = num; printf("%d=", num); if(num == 1){ printf("1\n"); return; } bool tag = true; int tn = (int)sqrt(1.0 * num); for(int i = 2; i <= tn; i++){ if(num == 1) break; if(!prime[i]){ int tCnt = 0; while(num % i ==0){ ++tCnt; num = num / i; } if(tCnt != 0){ if(tag) tag = false; else printf("*"); printf("%d",i); if(tCnt != 1) printf("^%d", tCnt); } } } if(num != 1){ if(num == tNum) printf("%d\n", num); else printf("*%d\n", num); } else printf("\n"); } int main(int argc, char* argv[]) { int num; while(~scanf("%d", &num)){ selectPrime(); countYue(num); } return 0; }