如何找到在C ++中的一些主要因素是什么?(How to find prime factors of

2019-08-31 12:29发布

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";
    }

Answer 1:

为什么你不尝试

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;
 }


Answer 2:

至少:

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

应该

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

在第一种方式,你想始终可以访问f[0]f[1]f[st!=y]



文章来源: How to find prime factors of a number in c++?