刚开始想直接求出n的阶乘,在从其结果里面查找相应的素数,可是发现数字太大,越界了,经改正如下:
My Code:
#include<iostream> using namespace std; int prime[100]; void prime_array() //生成素数表 { for(int i = 2, k = 0; i < 100; ++i) { int j = 2; for(; j*j <= i; ++j) { if(i % j == 0) break; } if(j*j > i) { prime[k++]=i; cout << i << "\t"; } } } int main() { int n; prime_array(); cout << endl; cout << "Enter some numbers(Ctr+Z to end):" << endl; while(cin >> n) { cout << n << "! = "; int cnt[100] = {0}; for(int i = 2; i <= n; ++i) { int temp = i; for(int j = 0; prime[j] <= i; ++j) //查找n的每个因子里素数 { while(temp % prime[j] == 0) //相应的素数存在,自增1 { ++cnt[j]; temp /= prime[j]; } } } for(i = 0; prime[i] <= n; ++i) cout << " " << cnt[i]; cout << endl; } return 0; }