user2372445
user2372445

Reputation: 101

How to stop Java from rounding my numbers so I can solve Problem3

So I've been doing some Project Euler lately, but for some reason, my code just doesn't work because Java keeps rounding my divsions.

public class Problem3 {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    double max = 0;
    double n = 600851475431.;

    for (double i = 2; i<Math.sqrt(n); i++){
        if (600851475431.%i == 0){
            if (isPrime (i) == true && i>max){
                max = i;
            }
        }
    }
    System.out.print(max);

}

public static boolean isPrime(double a){
    for (int i= 2; i<Math.sqrt(a); i++){
        if (a%i == 0){
            return false;
        }
    }
    return true;
}

First of all, 600851475431%168887 does not equal 0, but Java keeps thinking it that it does.

Upvotes: 0

Views: 1094

Answers (2)

Stephen C
Stephen C

Reputation: 718758

Actually, Java is right

  $ dc
    600851475431
    168887
    /
    p
    3557713
    168887
    *
    p
    600851475431
    ^D
  $

Since 3557713 * 168887 is exactly 600851475431, 600851475431 % 168887 is zero.

Upvotes: 1

user123
user123

Reputation: 9071

Tip: When you need accurate representations of numbers greater than 2^31 - 1, use long. When you need accurate representations of numbers greater than 2^64 - 1, use BigInteger.

600851475431 is between 2^39 and 2^41.

I'll let you make the conclusion.

edit
Another tip: if (600851475431.%i == 0){
Notice the .. This forces the number to be represented as a double. You have a variable n in there with an explicitly defined type. Use that.

Upvotes: 1

Related Questions