0
Python
No one likes homework, but your math teacher has given you an assignment to find the sum of the first N numbers. Letâs save some time by creating a program to do the calculation for you! Take a number N as input and output the sum of all numbers from 1 to N (including N).
9 Answers
+ 1
hint : just need a single loop
+ 2
Yup, no one likes Homework, especially if it's someone else's
+ 2
Paul K Sadler
đ€đ€đ€Łđ
+ 1
Paul K Sadler
it will throw wrong answer
mathematically you are right. but
write this way
print( int( ( N * ( N + 1 ) ) / 2 ) )
btw using A.P, bestđ
+ 1
NonStop CODING the code will not generate an error. For example for 100 the result will be 5050.0(float). If an Integer is required using int as you did will resolve that issue alternatively floor division can be used:
n * (1 + n) // 2
+ 1
Paul K Sadler
i said wrong answer, no error
floor division will work 100% trueđ€
+ 1
NonStop CODING Ah, got you, the description said nothing about an Integer result being required, good catch
+ 1
Thank you
I got itđ
0
print(n*(1+n)/2)
or a loop as NonStop CODING suggested above.