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

Viewed 411

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!

10 Answers

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  

If you have the curiosity to try a few partial sums, you immediately recognize the sequence of perfect squares. Hence, there are 11 terms and the last number is 21.

print(121, 21, 11)

More seriously:

i, s= 1, 1
while s <= 100:
    i+= 2
    s+= i

print(s, i, (i + 1) // 2)

Change your while loop so that you test and break before the top:

k=1
acc=0
while True:
  if acc+k>100:
    break
  else:
    acc+=k
    k+=2

>>> k
21
>>> acc 
100

And if you want the accumulator to be 121 just add k before you break:

k=1
acc=0
while True:
  if acc+k>100:
    acc+=k
    break
  else:
    acc+=k
    k+=2

Instead of

k = k + 2

say

if (sum <= 100):
  k = k +2

...because that is, after all, the circumstance under which you want to add 2.

To also count the numbers, have another counter, perhasp howManyNumbers, which starts and 0 and you add 1 every time you add a number.

Just Simply Change you code to,

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

Here, is the reason, the counter should be starting from 0 and the answer of the last printed number should be k-2 because when the sum exceeds 100 it'll also increment the value of k by 2 and after that the loop will be falls in false condition.

You can even solve it for the general case:

def sum_n(n, k=3, s =1):
    if s + k > n:
        print('Sum is', s + k)
        print('Last number', k)
        return
    sum_n(n, k + 2, s + k)
sum_n(int(input()))

You can do the following:

from itertools import count

total = 0
for i, num in enumerate(count(1, step=2)):
    total += num
    if total > 100:
        break

print('Sum is:', total)
print("last number:", 2*i + 1)

To avoid the update on k, you can also use the follwoing idiom

while True:
    total += k  # do not shadow built-in sum
    if total > 100:
        break

Or in Python >= 3.8:

while (total := total + k) <= 100:
    k += 2

Based on your code, this would achieve your goal:

n = 0
summed = 0
k = 1

while summed <= 100:
   n += 1
   summed = summed + k
   if summed <= 100:
       k = k + 2

print(f"Sum is: {summed}")
print(f"Last number: {k}") 
print(f"Loop count: {n}")

This will solve your problem without changing your code too much:

n = int()
counter_sum = 0
counter = 0
k = 1
while counter_sum <= 100:  
  k+= 2
  counter_sum =counter_sum+ k
  counter+=1
print('Sum is:', counter_sum)
print("last number:", k) 
print("number of numbers added:", counter) 

You don't need a loop for this. The sum of 1...n with step size k is given by

s = ((n - 1) / k + 1) * (n + 1) / k

You can simplify this into a standard quadratic

s = (n**2 - k * n + k - 1) / k**2

To find integer solution for s >= x, solve s = x and take the ceiling of the result. Apply the quadratic formula to

n**2 - k * n + k - 1 = k**2 * x

The result is

n = 0.5 * (k + sqrt(k**2 - 4 * (k - k**2 * x - 1)))

For k = 2, x = 100 you get:

>>> from math import ceil, sqrt
>>> k = 2
>>> x = 100
>>> n = 0.5 * (k + sqrt(k**2 - 4 * (k - k**2 * x - 1)))
>>> ceil(n)
21

The only complication arises when you get n == ceil(n), since you actually want s > x. In that case, you can test:

c = ceil(n)
if n == c:
    c += 1
Related