Sum(N) =1^1+2^2+3^3+...+N^N
Using Java,
How would I use BigInteger
to find the smallest integer N such that the value of Sum(N) is larger than 10^20?
I'm really stuck,please give me some advice
This is what I have so far:
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(i); // i^i
bSum = bSum.add(bTmp); // sum = i^i+ (i-1)^(i-1)+ ....
sSum = bSum.toString();
if ( sSum.length() >21) {
System.out.println("i="+i +" bSum ="+bSum);
break;
}//
}//end_for
return bSum; // result
} // end_bigFunctionExample_2
}
Looking at your code, you have a line bTmp.pow(2)
. That squares the numbers in your series, but you need to raise bTmp
to the bTmp
power. Java doesn’t seem to want to take a BigInteger
as an argument to pow
, but you could replace pow
with another for
loop.
Also, sSum.length() >30
looks like it will only occur if your sum is greater than or equal to 1029. Is there a reason you convert the number to a string each time through the loop, rather than comparing the number to 1020? Perhaps you could put something like bSum > bMax
as the test condition in your for
loop, rather than leaving it blank and exiting with a break
. Then you could make a new BigInteger bMax
and set it to 1020 at the start of your code.
For testing, you could set bMax
to something small, like 100, and see if your program gives the correct result. You can calculate the first few steps of the series by hand to check your program.