Project Euler#3获得数字的最大素因子 [英] Project Euler #3 Get largest prime factor of a number

查看:205
本文介绍了Project Euler#3获得数字的最大素因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,问题如下:

13195的主要因素是5,7,13和29.
最大数字的质数因子600851475143?

我为问题编写了一个代码,其逻辑和算法似乎正确,但似乎找不到错误,有代码。

I made a code for the question whose logic and algorithm seems correct but I can't seem to find the mistake, there's the code.

#include <iostream>

using namespace std;

int main()
{
    long int x = 600851475143;
    for(long int i=x-1; x%i; --i);
    cout << i;
    return 0;
}



RE:不知道'i'我学校的教师没有告诉我=)[不责备他们]

RE: Didn't know about the 'i' scope, Teachers in my school didn't tell me =) [not blaming them]

:Thanx为你的所有回复,我得到的答案。 =)

推荐答案

有两个小问题和一个大问题:

There are two small issues and one big issue:


  • 您的 i 变量超出了打印范围 - 语句的头部以语句本身结束。在这种情况下, i 在分号后不可见,因此您需要在之外声明

  • 您的变量不一定包含您想要放入的值 - long 32位类型,在许多平台上,它是。要使其至少为64位类型,请将声明更改为 long long

  • Your i variable is out of scope for printing - the scope of variables declared in the header of the statement ends with the statement itself. In this case, i is not visible after the semicolon, so you need to declare it outside the for
  • Your variables may not necessarily hold the values that you want to put into them - long is allowed to be a 32-bit type, and on many platforms, it is. To make it at least a 64-bit type, change the declaration to long long.

一旦你修复这些问题,你的代码将编译。但是,由于代码的第三个,大的问题,它需要花费很长时间才能运行:您的算法太慢了。

Once you fix these problems, your code will compile. However, it will take ages to run because of the third, big, problem with your code: your algorithm is too slow.

这篇关于Project Euler#3获得数字的最大素因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆