练习是:
设计一个程序,找出从 1 到 1000 的所有数,其质因数相加时总和为质数(例如,12 的质因数为 2、2 和 3,总和为 7,即质数) . 实现该算法的代码。
我应该使用非常基础的 C++,包括else/if, while and for loops
,当然还有声明一些函数。
不管像 2、3、5 这样的较小情况。我仍然没有得到正确的输出。输出是:
6 (sum of factors is 5 : OK)
8 (sum of factors is 6 : WRONG)
10 (sum of factors is 7: OK)
12 (sum of factors is 7: OK)
14 (sum of factors is 9: WRONG)
15 (sum of factors is 8: SO WRONG..)
ETC..
#include <iostream>
#include <math.h>
using namespace std;
bool CheckPrime (int x)
{
int count=0;
for(int i=1; i<=x; i++)
{
if( x%i==0 )
{count++;}
}
if ( count==2 )
{return true;}
else
{return false;}
}
int MakeSum (int x)
{
int Sum = 0;
for (double i=2; i<sqrt(x); i++)
{
if (CheckPrime(i))
{
for (double j=1; j<1000; j++)
{
int k = pow( i, j);
if ( (x % k) == 0 )
{
Sum = Sum + i;
}
}
}
}
return Sum;
}
int main() // Output cac so tim dc.
{
int SUM = 0;
for (int i=0; i < 1001; i++)
{
SUM = MakeSum(i);
if (CheckPrime(SUM))
{
cout << i << '\n';
SUM = 0;
}
}
}