[英]Finding the largest prime factor? (Doesn't work in large number?)
I am a beginner in C++, and I just finished reading chapter 1 of the C++ Primer.我是C++的初学者,刚看完C++ Primer的第一章。 So I try the problem of computing the largest prime factor, and I find out that my program works well up to a number of sizes 10e9 but fails after that eg600851475143 as it always returns a wired number eg2147483647 when I feed any large number into it.因此,我尝试计算最大质因数的问题,我发现我的程序在大小为 10e9 的情况下运行良好,但在 eg600851475143 之后失败,因为当我将任何大数输入其中时,它总是返回一个有线数字 eg2147483647。 I know a similar question has been asked many times, I just wonder why this could happen to me.我知道类似的问题已经被问过很多次,我只是想知道为什么这会发生在我身上。 Thanks in advance.提前致谢。
PS I guess the reason has to do with some part of my program that is not capable to handle some large number. PS 我想原因与我的程序的某些部分有关,该部分无法处理大量数据。
#include <iostream>
int main()
{
int val = 0, temp = 0;
std::cout << "Please enter: " << std::endl;
std::cin >> val;
for (int num = 0; num != 1; val = num){
num = val/2;
temp = val;
while (val%num != 0)
--num;
}
std::cout << temp << std::endl;
return 0;
}
Your int
type is 32 bits (like on most systems).您的int
类型是 32 位(就像在大多数系统上一样)。 The largest value a two's complement signed 32 bit value can store is 2 ** 31 - 1
, or 2147483647. Take a look at man limits.h
if you want to know the constants defining the limits of your types, and/or use larger types (eg unsigned
would double your range at basically no cost, uint64_t
from stdint.h
/ inttypes.h
would expand it by a factor of 8.4 billion and only cost something meaningful on 32 bit systems).带符号的 32 位二进制补码值可以存储的最大值是2 ** 31 - 1
或 2147483647。如果您想知道定义类型限制的常量和/或使用更大的常量,请查看man limits.h
类型(例如, unsigned
基本上可以免费将范围扩大一倍, stdint.h
/ inttypes.h
中的uint64_t
会将其扩展 84 亿倍,并且仅在 32 位系统上花费一些有意义的东西)。
2147483647
isn't a wired number its INT_MAX
which is defined in climits
header file. 2147483647
不是有线号码,它的INT_MAX
在climits
header 文件中定义。 This happens when you reach maximum capacity of an int
.当您达到int
的最大容量时,就会发生这种情况。
You can use a bigger data type such as std::size_t
or unsigned long long int
, for that purpose, which have a maximum value of 18446744073709551615
.为此,您可以使用更大的数据类型,例如std::size_t
或unsigned long long int
,它们的最大值为18446744073709551615
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.