gpt4 book ai didi

c++ - 程序不会运行非常大的数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:27 26 4
gpt4 key购买 nike

我对编程还很陌生,所以我用 C++ 编写了这个程序,它将接受一个数字并找到它的质因数,这很好用!除非它对于 int 变量来说太大了。现在我试着改变所有的int变量都变成long long变量所以没关系,但这似乎并不能解决问题。程序如下:

#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 就此而言,所以我期待您的简单易懂的回复。:)

最佳答案

我愿意成为您的程序正在运行。我敢肯定有人会突然出现并立即给你答案,但我希望这不会发生,这样你就可以体验到我遇到问题时所做的同样的事情 YEARS以前。

这样做:从 1 开始,从那里开始使用 2 的幂(1、2、4、8、16 等),然后继续前进,每次将输入数字加倍。它什么时候“停止运行”?它会逐渐变慢吗?

请对我的帖子或您自己的帖子发表评论,或编辑您自己的帖子,或发布答案,无论您只允许 56 个代表做什么。如果社区允许(当然,我希望社区进一步上课),我想通过一系列反复的反馈而不是典型的方式,轻轻地把你推向答案,因为这是一个明显独特的学习机会。

关于c++ - 程序不会运行非常大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3811645/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com