How to find prime factors of a number in c++?

2019-02-26 21:46发布

问题:

I am attempting project euler question number 3, and I don't get the desired result. My logic:

  1. List all the factors of the number 13195 and save them in an array.
  2. Check if each number in the array is a prime.
  3. If the number is found to be prime save it in an other array.
  4. display the contents of the second array.
  5. 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";
    }

回答1:

Why You Don't Try

for(x=1;x<=number;x++)
{
    if(number%x==0 && isPrime(x))
    {
        f[a] = x;
        a++;
    }
}

.. ..

int isPrime(int x)
{

 for(int i=2;i<=x/2;i++)
 {
   if(x%i==0)
   return 0;
 }
 return 1;
 }


回答2:

At least:

else if(f[st]%y!=0 && f[st!=y])

should be

else if(f[st]%y!=0 && f[st]!=y)

In the first way, you are trying to always access f[0] or f[1] by doing f[st!=y].