mirror of
https://bitbucket.org/Mattrixwv/projecteulerjava.git
synced 2025-12-06 17:13:58 -05:00
68 lines
2.6 KiB
Java
68 lines
2.6 KiB
Java
//ProjectEuler/Java/Problem16.java
|
|
//Matthew Ellison
|
|
// Created: 03-04-19
|
|
//Modified: 03-28-19
|
|
//What is the sum of the digits of the number 2^1000?
|
|
//Unless otherwise listed all non-standard includes are my own creation and available from https://bibucket.org/Mattrixwv/JavaClasses
|
|
/*
|
|
Copyright (C) 2019 Matthew Ellison
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Lesser General Public License as published by
|
|
the Free Software Foundation, either version 3 of the License, or
|
|
(at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Lesser General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Lesser General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
|
|
import mattrixwv.Stopwatch;
|
|
|
|
import java.math.BigInteger;
|
|
|
|
|
|
public class Problem16{
|
|
private static final Integer NUM_TO_POWER = 2; //The number that is going to be raised to a power
|
|
private static final Integer POWER = 1000; //The power that the number is going to be raised to
|
|
public static void main(String[] argv){
|
|
Stopwatch timer = new Stopwatch(); //To time the runtime of the algorithm
|
|
//Setup the other variables
|
|
BigInteger num = new BigInteger("0"); //The number to be calculated
|
|
Integer sumOfElements = 0; //The sum of all digits in the number
|
|
|
|
//Start the timer
|
|
timer.start();
|
|
|
|
//Get the number
|
|
num = BigInteger.valueOf(NUM_TO_POWER.longValue()).pow(POWER);
|
|
|
|
//Get a string of the number
|
|
String numString = num.toString();
|
|
|
|
//Add up the individual characters of the string
|
|
for(int cnt = 0;cnt < numString.length();++cnt){
|
|
sumOfElements += Integer.parseInt(numString.substring(cnt, cnt + 1));
|
|
}
|
|
|
|
//Stop the timer
|
|
timer.stop();
|
|
|
|
//Print the results
|
|
System.out.printf("%d^%d = %s\n", NUM_TO_POWER, POWER, num.toString());
|
|
System.out.println("The sum of the elements is " + sumOfElements.toString());
|
|
System.out.println("It took " + timer.getStr() + " to run this algorithm");
|
|
}
|
|
}
|
|
|
|
/* Results:
|
|
2^1000 = 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
|
|
The sum of the elements is 1366
|
|
It took 1.104 milliseconds to run this algorithm
|
|
*/
|