-8

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 power of 1000 (2^1000)?

Can anyone provide the solution or algorithm for this problem in java?

DonX
  • 16,093
  • 21
  • 75
  • 120
  • 8
    Ah, not homework. http://projecteuler.net/index.php?section=problems&id=16 – Serafina Brocious Dec 18 '08 at 09:47
  • 25
    If it's not homework, it's missing the entire point of Project Euler - why visit a math problem site if you're just going to ship the work off to other people? – Gareth Dec 18 '08 at 09:48
  • @BlackPanther - "mind your own business"? Who/where do you think you are? This *looks* like homework, and although I can see it isn't from Cody's comment it should be clearly marked as an Euler question in the body. – annakata Dec 18 '08 at 09:59
  • 2
    You haven't shown anything by which we can see that you have been trying this from last two days. – Adeel Ansari Dec 18 '08 at 10:03
  • @Gareth - can you solve problems in java without learning java?Do you think You are godfather of java.Even you had learned lot from others in this field.Why not begginers should ask a question from projecteuler to improve his or her knowledge –  Dec 18 '08 at 10:09
  • 2
    @BlackPanther : Pretty amazing how you killed everything you said by using that last sentence in your comment. – Learning Dec 18 '08 at 10:11
  • @GoldenDuck - as Adiel points out he didn't demonstrate any attempt at working this out, even as pseudocode, and if this was marked as a learner/homework/euler question clearly it shouldn't ask for a solution but pointers. – annakata Dec 18 '08 at 10:12
  • @BlackPanther - Take a look at my solution. I think this is what you are after. All the other answers using BigInts are cheating :) – bruno conde Dec 18 '08 at 11:36
  • 1
    this is getting really quite obnoxious – annakata Dec 18 '08 at 11:39
  • @BlackPanther - Indeed, they are better programmer and much more efficient than me. But you can't cover up things like that. I discourage giving solutions to this kind of questions, unless some efforts has been shown. Just think if its really were the homework question. – Adeel Ansari Dec 19 '08 at 02:27
  • 4
    Bleh. Posting code solutions for Project Euler questions just leaves a bad taste in my mouth. Not much better than just posting the answer to paste into the form. – Beska Mar 10 '10 at 14:08
  • Apart from the Java aspect, this is a duplicate of [this question](http://stackoverflow.com/questions/265258/how-to-avoid-scientific-notation-for-large-numbers) – Alnitak Dec 18 '08 at 11:37
  • projecteuler question – Rasmi Ranjan Nayak Apr 19 '16 at 20:12
  • in C/C++ lanuage: Take an array `arr[1000]`, then use `carry` for multiplication and addition. finally add all the `elements` in the array – Rasmi Ranjan Nayak Apr 19 '16 at 20:13

11 Answers11

9

Here is my solution:

public static void main(String[] args) {

    ArrayList<Integer> n = myPow(2, 100);

    int result = 0;
    for (Integer i : n) {
        result += i;
    }

    System.out.println(result);
}

public static ArrayList<Integer> myPow(int n, int p) {
    ArrayList<Integer> nl = new ArrayList<Integer>();
    for (char c : Integer.toString(n).toCharArray()) {
        nl.add(c - 48);
    }

    for (int i = 1; i < p; i++) {
        nl = mySum(nl, nl);
    }

    return nl;
}

public static ArrayList<Integer> mySum(ArrayList<Integer> n1, ArrayList<Integer> n2) {
    ArrayList<Integer> result = new ArrayList<Integer>();

    int carry = 0;

    int max = Math.max(n1.size(), n2.size());
    if (n1.size() != max)
        n1 = normalizeList(n1, max);
    if (n2.size() != max)
        n2 = normalizeList(n2, max);

    for (int i = max - 1; i >= 0; i--) {
        int n = n1.get(i) + n2.get(i) + carry;
        carry = 0;
        if (n > 9) {
            String s = Integer.toString(n);
            carry = s.charAt(0) - 48;
            result.add(0, s.charAt(s.length() - 1) - 48);
        } else
            result.add(0, n);
    }

    if (carry != 0)
        result.add(0, carry);

    return result;
}

public static ArrayList<Integer> normalizeList(ArrayList<Integer> l, int max) {
    int newSize = max - l.size();
    for (int i = 0; i < newSize; i++) {
        l.add(0, 0);
    }
    return l;
}

This code can be improved in many ways ... it was just to prove you can perfectly do it without BigInts.

The catch is to transform each number to a list. That way you can do basic sums like:

123456
+   45
______
123501
bruno conde
  • 47,767
  • 15
  • 98
  • 117
  • Is there any specific reason why you don't want to use BigInts? I'm thinking performance, but your version does not seem to be lightweight. – Morten Christiansen Dec 18 '08 at 11:42
  • lol. The reason is that this is a algorithm problem and you are suppose to find an answer that solves this without BigInts. BigInts is cheating ... – bruno conde Dec 18 '08 at 11:49
  • 10
    As you say, it is an algorithm/math problem. The 2^32 or 2^64 limit is just an implementation limit imposed by the machine's processor. I'd argue that using BigInts just gets you back closer to ideal arithmetic. – Boojum Dec 19 '08 at 00:35
  • 1
    I'd have to agree with Boojum on this one. – Morten Christiansen Dec 19 '08 at 09:48
  • 4
    With BigInts this is a trivial problem. bruno is quite correct in that this isn't quite the point of the problem. – cletus Mar 24 '09 at 23:50
  • For those curious, the answer is 1366. Also, this is an interesting problem to look at from a math-only perspective. For starters, you know the sum of the digits MOD 9 is the same as 2^1000 MOD 9 (divisibility rules), and if you analyze some patterns with powers of 2, you'll find that that's 7. Meanwhile, if you want to get an approximate size of the answer, first notice that there are 302 digits, and the last 301 follow a uniform distribution w/ μ=4.5, σ=2.87. The first digit is 1, so the approximate sum should be 1355.5 with standard deviation 49.8. Which comes pretty close. – Math Machine Apr 24 '22 at 17:57
7
int result = 0;

String val = BigInteger.valueOf(2).pow(1000).toString();

for(char a : val.toCharArray()){
    result = result + Character.getNumericValue(a);
}
System.out.println("val ==>" + result);

It's pretty simple if you know how to use the biginteger.

Himanshu
  • 31,810
  • 31
  • 111
  • 133
tony
  • 71
  • 1
  • 1
5

I won't provide code, but java.math.BigInteger should make this trivial.

Boojum
  • 6,592
  • 1
  • 30
  • 34
4

Create a vector of length 302, which is the length of 2^1000. Then, save 2 at index 0, then, double 1000 times. Just look at every index separetly and add 1 to the next index if the previous exeeds 10. Then just sum it up!

Robin
  • 41
  • 1
  • 3
    save 1 at index 0 - if you save 2, you will end up doubling by 1001 times. And 'exceeding' 10 is not completely correct - you have to carry the 1 over if the value exceeds 9 (e.g. is 10 or higher). – Joscha Dec 18 '12 at 01:48
4

This problem is not simply asking you how to find the nearest big integer library, so I'd avoid that solution. This page has a good overview of this particular problem.

Bill Zeller
  • 1,336
  • 1
  • 9
  • 13
1

something like that sould do it bute force: - although there is a nice analytic solution (think pen& paper) using mathematics - that may also work for numbers greater than 1000.

    final String bignumber = BigInteger.valueOf(2).pow(1000).toString(10);
    long result = 0;
    for (int i = 0; i < bignumber.length(); i++) {
        result += Integer.valueOf(String.valueOf(bignumber.charAt(i)));
    }
    System.out.println("result: " + result);
Andreas Petersson
  • 16,248
  • 11
  • 59
  • 91
1

How can 2^1000 be alternatively expressed?

I don't remember much from my maths days, but perhaps something like (2^(2^500))? And how can that be expressed?

Find an easy way to calculate 2^1000, put the result in a BigInteger, and the rest is perhaps trivial.

Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
1

Here is my code... Please provide the necessary arguments to run this code.

import java.math.BigInteger;

public class Question1 {
    private static int SumOfDigits(BigInteger inputDigit) {
        int sum = 0;
        while(inputDigit.bitLength() > 0) {
            sum += inputDigit.remainder(new BigInteger("10")).intValue();
            inputDigit = inputDigit.divide(new BigInteger("10"));       
        }                       
        return sum;
    }

    public static void main(String[] args) {
        BigInteger baseNumber = new BigInteger(args[0]);
        int powerNumber = Integer.parseInt(args[1]);
        BigInteger powerResult = baseNumber.pow(powerNumber);
        System.out.println(baseNumber + "^" + powerNumber + " = " + powerResult);
        System.out.println("Sum of Digits = " + Question1.SumOfDigits(powerResult));
    }

}    
Mark Hall
  • 53,938
  • 9
  • 94
  • 111
0

2^1000 is a very large value, you would have to use BigIntegers. The algorithm would be something like:

import java.math.BigInteger;
BigInteger two = new BigInteger("2");
BigInteger value = two.pow(1000);
int sum = 0;
while (value > 0) {
  sum += value.remainder(new BigInteger("10"));
  value = value.divide(new BigInteger("10"));
}
soulmerge
  • 73,842
  • 19
  • 118
  • 155
  • Fix compiler errors. Here. . while (value.compareTo(new BigInteger("0")) == 1) . . .AND . . .sum += value.remainder(new BigInteger("10")).intValue(); – Adeel Ansari Dec 18 '08 at 10:12
  • The contract of Comparable.compareTo() states that compareTo() should return values less than, equal to, or greather than 0. Even though BigInteger’s javadoc says it returns 1 you really should check for > 0. – Bombe Dec 18 '08 at 10:38
  • I actually think Bombe's solution is more elegant. It should even be a lot faster than mine. – soulmerge Dec 18 '08 at 10:48
  • To soulmerge, The good thing I found here, is no obvious use of char and String. I said 'obvious' because I haven't checked BigInteger source. To Bombe, good point. I agree. Thanks. – Adeel Ansari Dec 19 '08 at 02:19
0

Alternatively, you could grab a double and manipulate its bits. With numbers that are the power of 2, you won't have truncation errors. Then you can convert it to string.

Having that said, it's still a brute-force approach. There must be a nice, mathematical way to make it without actually generating a number.

ya23
  • 14,226
  • 9
  • 46
  • 43
-2
In[1162] := Plus @@ IntegerDigits[2^1000]
Out[1162] = 1366
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005