如何在C ++中找到数字的素因数? [英] How to find prime factors of a number in c++?
本文介绍了如何在C ++中找到数字的素因数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试项目euler问题3,但没有得到期望的结果.我的逻辑:
I am attempting project euler question number 3, and I don't get the desired result. My logic:
- 列出数字13195的所有因子并将它们保存在数组中.
- 检查数组中的每个数字是否都是质数.
- 如果发现该数字是素数,则将其保存在另一个数组中.
- 显示第二个数组的内容.
- 希望它只包含主要因素.
结果:第一个数组包含了所有预期的因素,第二个数组我认为与第一个数组重复或存在一些非素数,请帮忙!:)
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! :)
我的代码:
#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";
}
推荐答案
为什么不尝试
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;
}
这篇关于如何在C ++中找到数字的素因数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文