C ++首要循环测试以错误的方式执行

问题描述 投票:-3回答:3

我目前正面临一些挑战,正在寻找可以做的事情来测试我在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分钟左右(从这篇文章中)出发,直到我睡觉。

c++ for-loop primes
3个回答
1
投票

600851475143对于典型环境中的int类型而言太大,它的长度为32位,最多可以存储2000000000

二进制中的[6008514751431000 1011 1110 0101 1000 1001 1110 1010 1100 0111

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

其最高位是1,因此在典型环境中将其视为负数。

因此,i < thisnum变为false并且将不执行循环体。

您应使用至少为64位长的long long,并使用前缀为600851475143LLLL,它代表long long


-1
投票

您的代码看起来不错,应该可以。但是,对于for循环,您需要一对{},以防您将添加更多语句(例如std :: cout语句)

    // Check from 2 to n-1 
    for (int i = 2; i < n; i++) {
        if (n % i == 0)
            return false;
    }

-1
投票

600851475143太大,无法放入int。相反,您可以使用unsigned long long

unsigned long long Number = 600851475143ULL;
© www.soinside.com 2019 - 2024. All rights reserved.