输入正整数n(2<=n<=100),吧阶乘n!=1*2*3*4*…*n分解诚因子想成的形式,
从小到大输出各个素数(2、3、/5…)的指数。例如825=3*5^2*11应该表示成(0,1,2,0,1),表示分别有0、1、2、0、1个2、3、5、7、11。你的程序应忽略比最大素因子更大的素数。
输入样例:
5
53
输出样例:
5!=3 1 1
53!=49 23 12 8 4 4 3 2 2 1 1 1 1 1 1 1
代码如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
using namespace std;
int is_prime(int x)
{
for (int i = 2; i<=sqrt(x); i++)
if (x%i == 0)
return 0;
return 1;
}
int main()
{
int n, a[100], b[100];
while (cin >> n)
{
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
int Count = 0;
for (int i = 2; i <= n; i++)
{
if (is_prime(i))
a[Count++] = i;
}
for (int i = 1; i<=n; i++)
{
int m = i;
for (int j = 0; j<Count; j++)
{
while (m%a[j] == 0)
{
m /= a[j];
b[j]++;
}
}
}
cout << n << "!=";
int x;
for (x = Count; x >= 0; x--)
if (b[x])
break;
for (int i = 0; i<=x; i++)
cout << b[i] << " ";
cout << endl;
}
system("pause");
return 0;
}
我这里讲素数模板放到了while函数里面,无疑增加了运算量,因此,为减少运算量,直接将素数模板放到while函数外面,讲循环次数调整一下就可以。如下:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
using namespace std;
int is_prime(int x)
{
for (int i = 2; i<=sqrt(x); i++)
if (x%i == 0)
return 0;
return 1;
}
int main()
{
int n, a[100], b[100];
int Count = 0;
for (int i = 2; i <= 100; i++)
{
if (is_prime(i))
a[Count++] = i;
}
while (cin >> n)
{
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
for (int i = 1; i<=n; i++)
{
int m = i;
for (int j = 0; j<Count; j++)
{
while (m%a[j] == 0)
{
m /= a[j];
b[j]++;
}
}
}
cout << n << "!=";
int x;
for (x = Count; x >= 0; x--)
if (b[x])
break;
for (int i = 0; i<=x; i++)
cout << b[i] << " ";
cout << endl;
}
system("pause");
return 0;
}