0

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");
        }

    }



}

}

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
  • 8
    `"600851475143 "` contains a space – ernest_k Sep 21 '18 at 14:53
  • 2
    Not relevant to this specific issue, but you should learn about [how to compare Strings in Java](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). – azurefrog Sep 21 '18 at 14:54
  • 1
    @azurefrog Or even better, to not represent state by strings. Here a boolean would be just as good, and in the general case an Enum would be better than a string (typos would be caught by the compiler for example) – Aaron Sep 21 '18 at 14:57
  • `long` supports all 18 digit numbers and is easier to work with. – Peter Lawrey Sep 21 '18 at 15:11
  • 1
    check BigInteger comparison in in your code ` if(R==S)` seems buggy – Rahul B Sep 21 '18 at 15:37

3 Answers3

3

remove space in :

BigInteger N = new BigInteger("600851475143 ");

to be :

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

Remove the space in the string.

BigInteger N = new BigInteger("600851475143 ");

Would now be...

BigInteger N = new BigInteger("600851475143");
Peter Cooke
  • 105
  • 1
  • 10
1

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());
dehasi
  • 2,644
  • 1
  • 19
  • 31