Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0"

1.7k Views Asked by At

I'm writing a Java program to do some computation on big prime numbers, I get this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1.0" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.math.BigInteger.<init>(BigInteger.java:338) at java.math.BigInteger.<init>(BigInteger.java:476) at Solution.sumOfDivisorsModulo(Solution.java:24) at Solution.main(Solution.java:49)

public static BigInteger sumOfDivisorsModulo(BigInteger n){
    BigInteger sum = (n.add(one)).mod( MODULO);
    for (BigInteger test = n.subtract(one); test.compareTo(new BigInteger(Double.toString(Math.sqrt(n.longValue())))) >= 0; test.subtract(one))
    {
            if(n.mod(test).compareTo(zero) == 0)
            {
                    sum = sum.add(test);
                    sum = sum.add(n.divide(test));
                    sum = sum.mod(MODULO);
            }
    }
    return sum;
}

public static void main(String[] args) {
        int m = 2;
        int a = 0;
        primeList = new BigInteger[m];
        fillList(m); // fills the list primeList with prime number up to the mth
        BigInteger n = new BigInteger("1");
        for (int i = 0; i < m; i++){
                n.multiply(primeList[i].pow(a+i));
        }
        System.out.println(sumOfDivisorsModulo(n).toString()); // base10
}

one and zero are variables defined as BigInteger("0") and BigInteger("1"). Can you help me figure out what the problem is? I thank you in advance.

1

There are 1 best solutions below

11
On

The problem is here.

   new BigInteger(Double.toString(Math.sqrt(n.longValue())))

The Double.toString() call is going to give you a number string with a decimal point in it. But the BigInteger(String) constructor cannot parse a number string with a decimal point in it.

I don't understand what you are trying to do here, but the square root is liable to be a non-integer value.

If your intention is to convert the floating point (possibly non-integer) square-root value to an integer, then:

   // Round towards zero / truncate
   BigInteger.valueOf((long)(Math.sqrt(n.longValue())))  

or

   // Round to nearest
   BigInteger.valueOf((long)(Math.round(Math.sqrt(n.longValue()))))  

This should be more efficient than going via a string. And going via an int string is liable to overflow sooner.

Note however that for large enough values of n the square-root calculation will be noticeably inaccurate. There is no solution apart from finding or implementing your own BigInteger square-root method. However, if @Andreas is correct and you don't need to use BigInteger at all, this is moot.