javaintegerarithmeticexception

Project Euler #3 out of integer range java


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;
    }

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));

works and returns "29".

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

"600851475143 of type int is out of range".

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

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


Solution

  • 600851475143 of type int is out of range