0

Here is my code this should output (8477559501395327) but it is giving(2084842641) whats the problem here. I tried long instead of int but it gives some different answer

    int counter = 0;
    int counter2 =0;
    int k=203903;
    int result=0;
    int countequalk =0;
    int i=0;

   while(true){


        if( i % 2 != 0){
            counter++;
            if(counter<k){
                counter2=counter2+counter;
            }
            //System.out.println(counter+" "+i);

           if(counter>counter2&&counter<=counter2+k){

               result = result+i;
               countequalk++;
           }
           if(countequalk==k){
               break;
           }
        }
        i++;

    }

    System.out.println(result);
Shadiqur
  • 490
  • 1
  • 5
  • 18

1 Answers1

2

The number 8477559501395327 doesn't fit into an int - which supports values up to 2^31 - 1, as specified by Integer.MAX_VALUE. try using a long instead, which has a maximum value of 2^63 - 1, as indicated by Long.MAX_VALUE. This value is greater than 8477559501395327, so it fits. For even bigger numbers, better use BigInteger.

Óscar López
  • 232,561
  • 37
  • 312
  • 386