Anthony Hsieh
Anthony Hsieh

Reputation: 23

JAVA running too much time

This is my code,it has been one hour but it hasn't returned a value yet,is there anything wrong?

import java.math.BigInteger;

public class PROJECTV1 {  
    public static void main(String[] args) {    
        BigInteger bResult = bigFunctionExample_2();
            System.out.println(" => result_got:" + bResult);    
        System.out.println(); //newline     
    }// end_main

    public static BigInteger bigFunctionExample_2() {    
        BigInteger bSum = BigInteger.ZERO;
        BigInteger bTmp;
        String sSum;
        // BigInteger bResult =0;

        for (int i = 1; ; i++) {    
            bTmp = BigInteger.valueOf(i);    
            bTmp = bTmp.pow(2); // i^2    
            bSum = bSum.add(bTmp); // sum = i^2+ (i-1)^2 + ....

            sSum = bSum.toString();    
            if (sSum.length() > 30) {

                System.out.println("i=" + i + " bSum =" + bSum);    
                break;
            }

        }//end_for

        return bSum; // result
    }
    // end_bigFunctionExample_2    
}

Upvotes: 2

Views: 124

Answers (1)

mostruash
mostruash

Reputation: 4189

For that loop to break, it must reach 10^30 ~= 2^100. Sum of the squares of the first n natural numbers is approximately equal to n^3. So your loop will break approximately when i becomes 10^10 ~= 2^33. I guess int i is 32-bit so you MIGHT be are overflowing that integer, I didn't do the exact math but it's very possible.

If you go for a 64-bit variable (long?), which has an upper limit of approximately 10^19, you might have a chance it will be OK.

Edit: Here's the exact math from WolframAlpha.

Upvotes: 2

Related Questions