Project Euler – Problem # 16 – Solved with Go

What is the sum of the digits of the number 21000?

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

One Possible Solution: Go

package main

import "fmt"
import "math/big"
import "strings"
import "strconv"

func main() {

	x := big.NewInt(2)
	y := big.NewInt(1000)
	z := big.NewInt(0)

	result := new(big.Int).Exp(x, y, z)		// result is a 302 digit big.Int
	string_result := result.String()		// convert result to a string
	numbers := strings.Split(string_result, "")	// split the string

	Answer := 0
	for _, number := range numbers {	// enumerate thru the string of numbers
		x, _ := strconv.Atoi(number)	// convert string to an integer
		Answer += x			// add the individual integer to the Answer
	}

	fmt.Println(Answer)
}
Advertisements

Project Euler – Problem # 16 – Solved with Java

What is the sum of the digits of the number 21000?

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

**********

Helpful Links:

One Possible Solution: Java

import java.math.BigInteger;


public class Problem_16 {
	public static void main(String args[])
	{
		BigInteger result = BigInteger.ZERO;
		BigInteger two = BigInteger.valueOf(2);
		BigInteger one_thousand = BigInteger.valueOf(1000);
		result = pow(two, one_thousand);
		String string_result = new String(result.toString());
		
		int Answer = 0;
		for (int i = 0; i < string_result.length(); i++)
		{
		    Character c = new Character(string_result.charAt(i));
		    String s = c.toString();
		    int n = Integer.parseInt(s);
		    Answer = Answer + n;
		}

		System.out.println(Answer);

	}
	
	public static BigInteger pow(BigInteger base, BigInteger exponent)
	{
		BigInteger result = BigInteger.ONE;
		while (exponent.signum() > 0)
		{
			if (exponent.testBit(0)) result = result.multiply(base);
		    base = base.multiply(base);
		    exponent = exponent.shiftRight(1);
		}
		  return result;
	}

}

Project Euler – Problem # 16 – Solved with Python

What is the sum of the digits of the number 21000?

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

**********

Python makes this easy – there is no special handling for Big integers. In this problem, it is 302 digits long.

One Possible Solution: Python

# Python version = 2.7.2
# Platform = win32

def main():
    """Main Program"""
    result = 2 ** 1000
    string_result = str(result)

    Sum = 0
    for number in string_result:
        Sum = Sum + int(number)
        
    print Sum

if __name__ == '__main__':
    main()