我对编程很新,所以我用C ++制作这个程序,需要一个数字并找到它的主要因素,效果很好!除非它对于一个int变量来说太大了。现在我试着改变所有的int变量都是长的长变量所以没关系,但这似乎没有解决问题。程序如下:
#include <iostream>
using namespace std;
bool prime (long long recievedvalue) { //starts a function that returns a boolean with parameters being a factor from a number
long long j =1;
long long remainderprime = 0;
bool ended = false;
while (ended == false){ //runs loop while primality is undetermined
if (recievedvalue == 1){ //if the recieved value is a 1 it isn't prime
//not prime
return false;
break; // breaks loop
}
remainderprime=recievedvalue%j; //gives a remainder for testing
if ((remainderprime==0 && j>2) && (j!=recievedvalue || j == 4)){ //shows under which conditions it isn't prime
ended=true;
//not prime
return false;
}
else if (j==1){
j++;
}
else if ( recievedvalue==2 || j==recievedvalue ){ // shows what conditions it is prime
ended = true;
//prime
return true;
}
else {
j++;
}
}
}
long long multiple(long long tbfactor){ //factors and then checks to see if factors are prime, then adds all prime factors together
//parameter is number to be factored
long long sum = 0;
bool primetest = false;
long long remainderfact;
long long i=1;
while (i<=tbfactor){ //checks if a i is a factor of tbfactor
remainderfact=tbfactor%i;
if (remainderfact==0){ //if it is a factor it checks if it is a prime
primetest = prime(i);
}
if (primetest ==true){ //if it is prime it add that to the sum
sum += i;
primetest=false;
}
i++;
}
return sum;
}
int main()
{
long long input;
long long output;
cout << "Enter a number > 0 to find the sum of all it's prime factors: ";
cin >> input;
if (input == 0 || input <= 0){
cout << "The number you entered was too small."<< endl << "Enter number a number to find the sum of all it's prime factors: ";
cin >> input;
}
output = multiple(input);
cout << output << endl << "finished";
return 0;
}
现在可以肯定的是,问题是否与int无关。也像我说的那样,我对编程很新,而C就是这个问题,所以我期待你的回答容易理解。:)
答案 0 :(得分:4)
我愿意你的程序正在运行。我确信有人会在心跳中弹出并给你答案,但我希望它不会发生,这样你就可以体验到与我遇到问题时所做的相同的事情。前。
执行此操作:从1开始,然后使用2的幂(1,2,4,8,16等)从那里开始工作并继续前进,每次加倍输入数字。什么时候“停止运转?”它会逐渐变慢吗?
请回复我的帖子或自己发表评论,或编辑自己的帖子,或发布答案,无论你只允许56个代表做什么。如果社区允许它(当然我希望社区能够继续上课),我想通过一系列来回反馈而不是典型的方式,轻轻地推动您找到答案,因为这是一个明显独特的学习机会。
答案 1 :(得分:2)
如果你想找到一个数字是否是素数,这是一个快速的解决方案,
#include <iostream>
using namespace std;
#define ullong unsigned long long
bool prime (ullong x)
{
if(x <= 1)
return false;
ullong s = (ullong)sqrt(x);
for(ullong i=2;i<=s;i++)
if(x%i == 0)
return false;
return true;
}