C++素数循环测试以错误的方式执行

C++ prime loop test executes in false manner

本文关键字:方式 执行 错误 循环测试 C++      更新时间:2024-05-09

我目前正在接受一些挑战,并寻找一些东西来测试我在C++中的新能力,我决定主要做数学,在这种情况下是欧拉问题。下面是一些代码,可以找到给定数字的最大素数,但由于某种原因,它没有进入for循环,我甚至运行了cout << "Test" << endl;,但它不会打印语句,为什么会这样?

#include <iostream>
#include <string>
using namespace std;
int ReturnPFactors(int number)
{
int Factor{};
int thisnum = number;
for (int x = 0; x < thisnum; x++)
{
cout << "Here" << endl;
}
return Factor;
}
bool isPrime(int n)
{
// Corner case 
if (n <= 1)
return false;
// Check from 2 to n-1 
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
int main()
{
//should be looking for 6857
int Number = 600851475143;
cout << ReturnPFactors(Number) << endl;
return 0;
}

如果你有任何问题,我会在接下来的30分钟左右(从这篇帖子(,在我睡觉之前回答。

600851475143对于典型环境中的int类型来说太大,它是32位长的,最多可以存储2147483647

二进制中的CCD_ 5是CCD_。

在典型环境中,它被截断为32位长:1110 0101 1000 1001 1110 1010 1100 0111

它的最高位是1,因此在典型环境中被视为负数。

在此之前,i < thisnum变为false,循环体将不会被执行。

您应该使用至少64位长的long long和前缀为LL(代表long long(的600851475143LL