Project Euler | Problem 16 | Power digit sum



Problem Description:


2^15= 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000 ?

Solution of Project Euler Problem 16 - Power digit sum
Figure1

Concept:


As result of 2^1000 is very big and we can't store it in any primitive data type so to solve this problem we need to use methods of BigInteger class present in java.math.* package.

Java Program:



package com.javamultiplex.projecteuler;
import java.math.BigInteger;
/**
*
* @author Rohit Agarwal
* @category Project Euler Problems
* @Problem 16 - Power Digit Sum.
*
*/
public class Problem16 {
public static void main(String[] args) {
int a = 2;
int b = 1000;
// Converting Integer to BigInteger.
BigInteger number = new BigInteger(String.valueOf(a));
// Getting 2^1000.
BigInteger power = number.pow(b);
// Converting BigInteger to String.
String powerInString = String.valueOf(power);
int length = powerInString.length();
int sum = 0;
int temp = 0;
for (int i = 0; i < length; i++) {
// Converting char to int.
temp = powerInString.charAt(i) - 48;
sum += temp;
}
System.out.println("The sum of the digits of the number 2^1000 is : " + sum);
}
}
view raw Problem16.java hosted with ❤ by GitHub

Output:


Answer of Project Euler Problem 16 - Power digit sum
Figure2

Similar Problems:





References:


https://projecteuler.net/problem=16
https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

Thank you friends, I hope you have clearly understood the solution of this problem. If you have any doubt, suggestion or query please feel free to comment below. You can also discuss this solution in our forum.

About Author:

I am simple guy with lot of ambitions. My main motive is to share whatever knowledge I have related to programming. With me you can easily learn how to solve any programming problem in Java.You can connect with me on social networking sites also.


Let's Get Connected: Linkedin | Facebook |

Project Euler | Problem 16 | Power digit sum Project Euler | Problem 16 | Power digit sum Reviewed by Rohit Agarwal on 10/15/2017 Rating: 5

2 comments:

  1. why did you use -48

    ReplyDelete
  2. Because ascii value of 0-9 digit is 48-57 and on subtracting two ascii values, we will get integer.

    ReplyDelete

Please provide your valuable comments. If you have any suggestion please share with me I will work on it and if you have any question or doubt please ask, don't hesitate. I am your friend, i will clarify all your doubts.

Powered by Blogger.