项目Euler#3超出整数范围java [英] Project Euler #3 out of integer range java

查看:197
本文介绍了项目Euler#3超出整数范围java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该代码应该回馈最大的素数。
有关此任务的更多信息: https://projecteuler.net/problem=3

The code is supposed to give back the biggest prime number. More about the task here: https://projecteuler.net/problem=3

int checkFactors(double na) {

        long n = (long) na;
        int biggestPrimeFactor = 0;
        for (int i = 1; i < n; i++)
            if (n % i == 0 && isPrimFaktor(i) && i > biggestPrimeFactor)
                biggestPrimeFactor = i;

        return biggestPrimeFactor;
    }

boolean isPrimeFactor(int n) {

        int length= 0;
        for (int i = n; i > 0; i--)
            if (n % i == 0)
                length++;

        if (length== 2)
            return true;
        return false;
    }

我决定将checkFactors()的参数设为double,因为我试图测试我的代码无法正常工作的原因。

I decided to make the parameter of checkFactors() a double because I tried to test why my code didn't work properly.

System.out.println(checkFactors(13195));

工作并返回29。

但是, System.out.println(checkFactors(600851475143));
不起作用,

However, System.out.println(checkFactors(600851475143)); does not work,

int类型的600851475143超出范围。

"600851475143 of type int is out of range".

System.out.println(checkFactors(600851475143.0));

确实编译但在几秒钟之后给我一个ArithmeticException。

does compile but gives me after a couple of seconds an ArithmeticException.

推荐答案

类型为int的600851475143超出范围


  • 此数字大于 int 可以存储。将 .0 附加到该数字会将该数字转换为 double ,其中可以表示该数字

  • 您可以执行 checkFactors(600851475143d)而不是 .0 数字是双倍而不是int

  • This number is bigger than int can store. Appending .0 to the number converts the number into a double which can represent that number
  • Instead of .0 you can do checkFactors(600851475143d) which ensure the number is a double and not an int

这篇关于项目Euler#3超出整数范围java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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