1

I was given the following question in an interview...

Compute the following sum:
1/2 + 1/4 + 1/8 + ... + 1/1048576    

I was told that this was a logic question and they weren't looking for the source code, however my answer was the following...

    private static double computeSum(){
        double x = 0.0;
        for(double i=2; i<=1048576; i*=2){
            x += (1 / i);
        }
        return x;         
    }

What is the correct logical answer to this question?

4
  • 1
    I have the feeling that with the way doubles are implemented, you'll end up with exactly 1. Power series convergence coupled with limited precision. I've also added the interview-questions tag to your question. Commented Apr 16, 2012 at 11:04
  • yea, the answer is something like 0.99999 Commented Apr 16, 2012 at 11:05
  • 1
    It's a convergent serie, it's sum is something like a0*(1/q), where a0 is a first elem of the sequence, q = a0/a1. Don't remember actually, it's from high school program :) if such a serie (with q=1/2) is infinite, the sum of it is exactly 1. Commented Apr 16, 2012 at 11:07
  • 1
    en.wikipedia.org/wiki/Geometric_series: (1-0.5^21)/0.5 - 1. Commented Apr 16, 2012 at 11:13

4 Answers 4

11

I fi was presented with that sum I would say the answer is 1 minus the nth term, so in your case it's

1 - 1/1048576 = 1048575/1048576

I wouldn't do any maths or code or anything. I guess that's the kind of answer they were looking for.

I might show some "working" by saying 1/2 + 1/4 = 3/4 = 1 - 1/4; // Edit here

1/2 + 1/4 + 1/8 = 7/8 = 1 - 1/8
Sign up to request clarification or add additional context in comments.

Comments

3

The sum:

1/2 + 1/4 + 1/8 + ... + 1/1048576

is equivalent to:

(1 + 2 + ... 2 ^ 20) / (2 ^ 20) - 1 =
(2 ^ 21 - 1) / (2 ^ 20) - 1 =
2 - 1 / (2 ^ 20) - 1 =
1 - 1 / (2 ^ 20) ~= 0.99999

The sum will tend to one if the length of the series is increased.

Comments

0

They are adding fractions together until they come up with a fraction 1/1048576 which has a very negligible value. This means that the answer to the above will be very close to 1 but not exactly one.

Comments

0

This is a simple convergent geometric series

  s=a+ar+ar^2+ar^3+... to infinity

So the sum is

s=1/(1-r) where in this case r =1/2

However, we are seeking s-a, since the given series starts at 1/2 and not at 1. hence

s-a = 1/(1-r) - a = 1/(1-1/2) -1 = 1.

Why they call it a logic problem is not clear to me, except that they may want an explanation why the given geometric series converges -- which is a simple proof: i.e. the ratio between any two consecutive terms is a constant less than 1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.