这是我到目前为止所做的:
//project Eular Problem 4: Prime Factors
#include<iostream>
#include<cmath>
typedef unsigned long long int uint_64;
using namespace std;
void storeFactors(uint_64 factors[], uint_64 num)
{
for(uint_64 i=0;i*i<num;i++
factors[i]=1; //assign 1 to all the values
for(uint_64 j=2; j*j<num;j++){
if(num%j!=0)
factors[j]=0; //assign 0 to non-factors
}
}
//Sieve of Eratosthenes to generate primes
void gen_primes(uint_64 arr[],uint_64 firstElement, uint_64 lastElement, uint_64 size)
{
for(uint_64 i=0;i<size;i++) //assigning 1 to all the values
arr[i]=1;
for(uint_64 i=2;i*i<=lastElement;i++){ //loop until the square-root of n
if(arr[i])
for(uint_64 j=i;j*i<=lastElement;j++) //eliminate multiples by assigning them 0
arr[j*i]=0;
if(firstElement==1)
arr[firstElement]=0;
}
}
void arrayComp(uint_64 factors[],uint_64 primeArray[], uint_64 size)
{
for(uint_64 i=2; i<=size; i++){
if(factors[i] && primeArray[i]){
cout<<i<<endl;
}
}
}
void processFactors(uint_64 num)
{
uint_64 size = sqrt(num);
uint_64 *factors = new uint_64[size];
uint_64 *primeArray = new uint_64[size];
storeFactors(factors, num);
gen_primes(primeArray, 2, num, size);
arrayComp(factors, primeArray,size);
delete [] factors;
delete [] primeArray;
}
int main()
{
uint_64 number;
cout<<"Enter a number: "<<endl;
cin>>number;
cout<<"The prime factors of "<<number<<" are: "<<endl;
processFactors(number);
return 0;
}
我尝试采用筛选方法来计算因子。所有非因子都被赋值为0.如果数字既是输入的因子又是素数,则ArrayComp显示数字。
我遇到的问题是输出不完整,程序遇到分段错误。例如,10的因子是5和2,但它显示100的相同答案。
编辑:我不太自信的另一件事是阵列的大小。这个程序显示3是21的主要因素,而不是7,但如果我将大小增加1,则显示3和5(不正确)答案 0 :(得分:7)
100的素因子与10的素因子相同,只有多重性不同。
您的代表似乎无法存储重复的因素。
答案 1 :(得分:1)
uint_64 size = sqrt(num);
uint_64 *factors = new uint_64[size];
uint_64 *primeArray = new uint_64[size];
错误的保留金额。
例)
num = 10
size = 3
因子10 = 2,5
if(factors[i] && primeArray[i]){
cout<<i<<endl;
}
因素[5]?那么数组大小是3(0,1,2)