Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12201

How to test if a BigDecimal object is divisible by another BigDecimal in Java?

$
0
0

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("1.0"); // Adjusted increment for simplicity        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 or improvements on my current approach would be appreciated.


Viewing all articles
Browse latest Browse all 12201

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>