[英]Function to check for largest prime factor returning returning 0 when using large numbers c++
This is for the third problem in Project Euler.这是欧拉计划中的第三个问题。 I suspect that it only returns 0 because I assigned 0 to the 'returnum' variable on initialization.
我怀疑它只返回 0,因为我在初始化时将 0 分配给了 'returnum' 变量。 My code works fine in smaller numbers, but it isn't working for a large number (600851475143) which is needed to get the correct answer.
我的代码在较小的数字下工作正常,但它不适用于获得正确答案所需的大量数字 (600851475143)。
Is this for the size of int?这是为了 int 的大小吗? If so what data type should I use?
如果是这样,我应该使用什么数据类型?
Here is my code:这是我的代码:
int problem3(long int num) {
long int returnum;
for (int i = 2; i < num; ++i) {
if (num % i == 0 && primecheck(i)) {
returnum = i;
}
}
return returnum;
}
And this is my 'primecheck' function:这是我的“primecheck”功能:
bool primecheck(long int num) {
for (int i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}
Edit: I have tried to change the datatype but when I do, it just doesn't respond, showing an empty console for a few minutes, then crashing.编辑:我试图更改数据类型,但是当我这样做时,它只是没有响应,显示一个空控制台几分钟,然后崩溃。
The maximum value for a variable of type int is 2147483647, whereas the max value of float is : 3.40282e+38 or 0x1.fffffep+127. int 类型变量的最大值为 2147483647,而 float 类型的最大值为:3.40282e+38 或 0x1.ffffep+127。 You could use double also.
你也可以使用 double 。
long long problem3(long long num) {
long long returnum;
for (long long i = 2; i < num; ++i) {
if (num % i == 0 && primecheck(i)) {
returnum = i;
}
}
return returnum;
}
And this is my 'primecheck' function:这是我的“primecheck”功能:
bool primecheck(long long num) {
for (long long i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}
Fundamental Types (C++)基本类型 (C++)
tested!测试! OK!
好的! VS2017
VS2017
#include "stdafx.h"
#include <stdio.h>
bool primecheck(long long num);
long long problem3(long long num);
bool primecheck(long long num) {
for (long long i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}
long long problem3(long long num) {
long long returnum;
for (long long i = 2; i < num; ++i) {
if (num % i == 0 && primecheck(i)) {
returnum = i;
}
if (i % 100000 == 0) {
printf("tick - %lld\n", i);
}
}
return returnum;
}
int main()
{
printf("out number %lld\n", problem3(600851475143));
return 0;
}
32 037 210 000 - screenshot 10 000 000 per/sec . 32 037 210 000 - 截图 10 000 000 每秒。 (in this moment > (long)2^32) and what you want with this program?
(此时>(长)2^32)以及你想要这个程序做什么? wait 65K sec?
等待 65K 秒? (18 hours) may be need use math algorithm for best time ?
(18 小时)可能需要使用数学算法以获得最佳时间?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.