I'm working on a problem from a Java textbook which asks to find the first 10 numbers with 50 decimal digits that are divisible by 2 or 3. Here is my code:
import java.math.*;
public class Divisible {
public static void main(String[] args) {
BigDecimal numbers = new BigDecimal("0.00000000000000000000000000000000000000000000000000");
BigDecimal number2 = new BigDecimal("2.0");
BigDecimal number3 = new BigDecimal("3.0");
BigDecimal increment = new BigDecimal("0.00000000000000000000000000000000000000000000000001");
int count = 0;
while (count < 10) {
boolean isDivisibleBy2 = isDivisible(numbers, number2);
boolean isDivisibleBy3 = isDivisible(numbers, number3);
if (isDivisibleBy2 || isDivisibleBy3) {
System.out.println(numbers);
count++;
} else {
System.out.println("No divisor.");
}
numbers = numbers.add(increment);
}
}
private static boolean isDivisible(BigDecimal number, BigDecimal divisor) {
BigDecimal remainder = number.remainder(divisor);
return remainder.compareTo(BigDecimal.ZERO) == 0;
}
}
But this code goes in an infinite loop of priting "No divisor."
I think the problem is in isDivisible
method, which checks divisibility by using the remainder
method.
Any advice on my current approach would be appreciated.
You don't have an infinite loop. Your increment is just so small that it just takes many, many, many iterations for the division to finally find a number that's divisible by 2 or 3. If I change the increment to 0.01 I get results almost immediately. With 0.00001 it takes seconds to find results. I don't know how long it takes to find the first result (2) with your increment, but it's not seconds, not even hours, and probably not even weeks - it could well be over a year. (The printing of the message doesn't help there either.)