Ali Mirzade
Ali Mirzade

Reputation: 3

how to correct this java code which uses BigInteger?

I am trying to solve the 3rd problem of project Euler that needs a 12 digits number and the problem is that the code I wrote isn't running :( would you help me figure it out ? The error is so confusing:

Exception in thread "main" java.lang.NumberFormatException: For input string: "51475143 "
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.math.BigInteger.<init>(BigInteger.java:546)
    at java.base/java.math.BigInteger.<init>(BigInteger.java:675)
    at Euler.main(Euler.java:9)

Here's the whole code:

public static void main(String[] args) {

    BigInteger N = new BigInteger("600851475143 ");
    BigInteger PrimeNumber;

    for(long i=2;i<250000;i++)
    {
        String code=" ";
        for(long j=2;j<i;j++)
        {

            if(i%j==0)
                code="exit";
        }
        if(code=="exit")
            break;

        PrimeNumber=BigInteger.valueOf(i);
        BigInteger R=N.remainder(PrimeNumber);
        if(R.equals(0))
        {
            System.out.println(N.divide(R));
            System.out.println("That's The answer");
        }

    }



}

}

Upvotes: 0

Views: 105

Answers (3)

dehasi
dehasi

Reputation: 2773

As it was answered above, there was a space symbol in your string. To avoid such mistypes it's worth to use the String.trim() method which removes whitespaces in the beginning and at the end of the string.

Smth like:

String num = "600851475143 ";
BigInteger N = new BigInteger(num.trim());

Upvotes: 1

Peter Cooke
Peter Cooke

Reputation: 105

Remove the space in the string.

BigInteger N = new BigInteger("600851475143 ");

Would now be...

BigInteger N = new BigInteger("600851475143");

Upvotes: 1

Abdessamad HALLAL
Abdessamad HALLAL

Reputation: 121

remove space in :

BigInteger N = new BigInteger("600851475143 ");

to be :

BigInteger N = new BigInteger("600851475143");

Upvotes: 3

Related Questions