Friday, 15 July 2011

Project Euler 3 Java ArithmeticException -



Project Euler 3 Java ArithmeticException -

this gets prime factors of number keeps going , outputs negative factors of number reason, help? link question here: http://projecteuler.net/problem=3

public static void main(string[] args) { long number = 600851475143l; divchecker(number); } public static void divchecker(long n) { int div = 2; while (div * div < n) { if (n % div == 0) { primechecker(div); div++; } else { div++; } } } public static void primechecker(long n) { int div = 2; while (div * div < n) { if (n % div != 0) { div++; } else { break; } } if (n % div != 0) { system.out.println(n); } }

output here:

71 839 1471 6857 -716151937 -408464633 -87625999 -10086647 -5753023 -1234169 -486847 -104441 -59569 -6857 -1471 -839 -71 -1 exception in thread "main" java.lang.arithmeticexception: / 0 @ bucky.divchecker(bucky.java:13) @ bucky.main(bucky.java:7)

your multiplications int overflowing, yielding "negative" factors.

declare div variables long instead of int.

long div = 2; // 2 places in code

with change, output only, , windows calculator verifies product original number factor, 600851475143l:

71 839 1471 6857

java

No comments:

Post a Comment