I am attempting project euler question number 3, and I don't get the desired result. My logic:
- List all the factors of the number 13195 and save them in an array.
- Check if each number in the array is a prime.
- If the number is found to be prime save it in an other array.
- display the contents of the second array.
- Hope it contains only prime factors.
RESULT: The first array contains all the factors as expected, The second I think duplicates the first array or slips in some non-primes, Please help! :)
My code:
#include <iostream>
using namespace std;
long int x,y=2;
long int number=13195;
long int f[1000000],ff[1000000];
int st=1;
int open=0;
int open2=0;
int a=0;
bool isprime;
int main()
{
for(x=1;x<=number;x++)
{
if(number%x==0)
{
f[a] = x;
a++;
}
}
while(st<=16)
{
while(y<f[st])
{
if(f[st]%y==0 && f[st]!=y)
{
break;
}
else if(f[st]%y!=0 && f[st!=y])
{
ff[open] = f[st];
}
y++;
}
open++;
st++;
}
for(open2=0;open2<open;open2++)
{
cout<<ff[open2]<<" is a prime factor of "<<number<<"\n";
}
return 0;
}
using this for finding the prime works:
while(st<=a){
int k = f[open];
for(int i=2;i<k;i++)
{
if(k%i==0)
{
isprime = false;
break;
}
else if(f[open]!=0 && f[open]%i!=0 && f[open]!=i)
{
isprime =true;
}
}
if(isprime==true)
{
ff[st] = k;
open3++;
isprime = false;
}
open++;
st++;
}
cout<<"The primes of them are "<<open3<<"."<<"\n";
cout<<"Press RETURN to show them."<<"\n";
cin.get();
for(open2=0;open2<=open3;open2++)
{
cout<<ff[open2]<<" is a prime factor of "<<number<<"."<<"\n";
}