我做了以下练习:
设计一个程序,查找从1到1000的所有数字,其素数因子加在一起时,总和为素数(例如,12的素数因子为2,2和3,总和为7,其中是素数)。实现该算法的代码。
我的代码:
#include <iostream>
#include <string>
//function prototype
int PrimeFactor(int number);
bool isPrime(int PrimeOrNot);
int main() {
int i;
for (i = 0; i < 1000; i++)
PrimeFactor(i);
}
int PrimeFactor(int number) {
int i;
int firstsplit = 0;
int secondsplit = 0;
int nextSplit = 0;
int afternextsplit = 0;
int sum = 0;
for (i = 2; i < number; i++) //loop that find the number that split it to two number , the purpose is for buiding the factor tree.
{
if (number % i == 0) {
firstsplit = number / i;
secondsplit = number / firstsplit;
if (isPrime(firstsplit))
sum = sum + firstsplit;
if (isPrime(secondsplit))
sum = sum + secondsplit;
break;
}
}
if (isPrime(firstsplit) == false) //check if the splitted number is not already a factor from previous loop.
{
while (isPrime(firstsplit) == false) {
for (i = 2; i < firstsplit; i++) //loop that continue to split the splitted number for the purpose of prime factors.
{
if (firstsplit % i == 0) {
nextSplit = firstsplit / i;
afternextsplit = firstsplit / nextSplit;
if (isPrime(nextSplit))
sum = sum + nextSplit;
if (isPrime(afternextsplit))
sum = sum + afternextsplit;
}
}
}
}
}
bool isPrime(int PrimeOrNot) {
int i;
for (i = 0; i < PrimeOrNot; i++) {
if (PrimeOrNot % i == 0)
return false;
}
return true;
}
问题:
我认为我的程序似乎不那么有效,因为有很多变量,我想它可以用更少的时间来完成。任何人都可以通过一个素因子树找到另一种方法来帮助我吗?
Prime树示例:
16
/ \
4 4
/\ /\
2 2 2 2
答案 0 :(得分:0)
这是解决任务的一种有效方法。我正在使用筛子,您可以参考https://www.quora.com/What-is-the-sieve-in-c++/answer/Ankit-Vallecha
#include<iostream>
#include<cmath>
using namespace std;
#define N 1000
int flag[N+1]; // flag[i] =0 means i is prime, flag[i] =1 means i is not prime
int primes[N+1]; // primes[i] contains the (i+1)th prime, like prime[0]=2, prime[1]=3, prime[2]=5...
int len=0; // len determines the length of primes array filled
void sieve(){ // this function calculates all the primes less than N in primes array and number of primes is in len.
for( int i=2; i<=sqrt(N); i++ ){
if( flag[i] == 0 )
for( int j=2*i; j<=N; j+=i )
flag[j] = 1;
}
// now after this first loop flag[i] is ready to determine prime
for( int i=2; i<=N; i++ )
if( flag[i] == 0 )
primes[len++] = i;
// now primes contain the primes
}
bool isFactorSumPrime( int x ){ // this functions check whether sum of prime factors is prime or not
int sum = 0; // sum of factors
for( int i=0; i<len; i++ ){
if( x==1 ) break; // x has no prime factors
while( x%primes[i] == 0 ){ // if primes[i] is factor of x
sum += primes[i];
x /= primes[i];
}
}
return !flag[sum];
}
int main(){
sieve();
for( int i=2; i<=N; i++ )
if( isFactorSumPrime(i) == true )
cout << i << endl;
return 0;
}