IF YOU THINK, THE BIGINTEGER IS AND / OR DOES NOT HAVE IT / STILL TAKES HOW TO USE IT, THIS ALGORITHM IS THE WAY.
Think about how you would calculate 2 ^ 1000 manually. You start with 2 ^ 1 and multiply by two. Now note that the number of digits of two degrees increases by 1 for AT LEAST every 3 degrees (maybe after 4 degrees, for example, from 1024 to 8192). So make a jagged 2D array like this
int a[][]= new int[1000][]; for(int i=0;i<1000;i++) { a[i]= new int[1+(i/3)]; }
Then initialize [0] [0] to 2. After that, you want to write a for loop so that each line is filled from the rightmost spot. Therefore, make the two variables “digit” and “carry over”. The digit is the number that you will enter in the line that you are working on, and the hyphenation is the one you are going to use for the next calculation, and add to the product 2 and any digit that you multiply. Be careful with the order when you update the digit, transfer and reinitialize them to zero after each calculation. I think the hardest part comes up with the limitations of the for loop, so it matches each of the three things. You can make it simpler by simply making a triangular gear array that grows one row. I did it like that. Here is all my code.
import java.util.*; public class ProjectEuler16 { public static void main(String[] args) { long t1=System.currentTimeMillis(); ProjectEuler16 obj = new ProjectEuler16(); System.out.println(obj.bigNumHandler()); long t2= System.currentTimeMillis(); System.out.println(t2-t1); } int bigNumHandler() { int a[][] = new int[1000][]; for(int i=0;i<1000;i++) { a[i]= new int[1+(i/3)]; } a[0][0]=2; for(int i=1;i<1000;i++) { int carry=0; int digit=0; int f=0; if(i%3==0) { f=1; } for(int j=a[i-1].length-1+f;j>=0;j--) { if(j==0&f==1) { a[i][0]=carry; } else { digit=((2*a[i-1][jf])+carry)%10; carry=((2*a[i-1][jf])+carry)/10; a[i][j]=digit; } } } int sum=0; for(int k=0;k<a[999].length;k++) { sum=sum+a[999][k]; } return sum; } }
Please note that the last line lists the numbers for 2 ^ 1000. I think you can figure out how to sum the numbers. The answer to this question took about 5 seconds.
source share