如何在c++中找到一个数字的素数因子

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

本文关键字:数字 一个 c++      更新时间:2023-10-16

我正在尝试项目欧拉问题3,我没有得到想要的结果。我的逻辑:

  1. 列出数字13195的所有因数并保存为数组
  2. 检查数组中的每个数字是否为素数。
  3. 如果发现数字是素数,将其保存在其他数组中。
  4. 显示第二个数组的内容。
  5. 希望它只包含质因数。

结果:第一个数组包含预期的所有因子,第二个我认为重复了第一个数组或在一些非素数中滑动,请帮助!:)

我代码:

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

用这个来求素数是有效的:

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

为什么不试试

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

至少:

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

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

在第一种方式中,您总是试图通过执行f[st!=y]来访问f[0]f[1]

相关文章: