Search code examples
pythonalgorithmmathsum

Sum of 1+3+5...+n until the sum exceeds 100


Then the sum and the last added number and the number of numbers added must be printed.

I am currently stuck, I managed to get the sum part working. The last added number output is printed "23" but should be "21". And lastly, how can I print the number of numbers added?

Output goal: 121, 21, 11

Here is my code:

n = int()
sum = 0
k = 1
while sum <= 100:
  if k%2==1:
    sum = sum + k
  k = k + 2
print('Sum is:', sum)
print("last number:", k) 

Edit: Would like to thank everyone for their help and answers!


Solution

  • Note, that (you can prove it by induction)

    1 + 3 + 5 + ... + 2 * n - 1 == n**2
    <-----    n items    ----->
    

    So far so good in order to get n all you have to do is to compute square root:

    n = sqrt(sum) 
    

    in case of 100 we can find n when sum reach 100 as

    n = sqrt(100) == 10
    

    So when n == 10 then sum == 100, when n = 11 (last item is 2 * n - 1 == 2 * 11 - 1 == 21) the sum exceeds 100: it will be

    n*n == 11 ** 2 == 121
    

    In general case

    n = floor(sqrt(sum)) + 1
    

    Code:

    def solve(s):
        n = round(s ** 0.5 - 0.5) + 1;
        
        print ('Number of numbers added: ', n);
        print ('Last number:             ', 2 * n - 1)
        print ('Sum of numbers:          ', n * n)
        
    solve(100)
    

    We have no need in loops here and can have O(1) time and space complexity solution (please, fiddle)

    More demos:

    test : count : last : sum
    -------------------------
      99 :    10 :   19 : 100
     100 :    11 :   21 : 121
     101 :    11 :   21 : 121