+ 2

Can you write a program for adding a series of natural numbers without using any kind of loop?

solutions using bitwise operators are most welcome.

3rd Mar 2018, 3:06 AM
Anjum Chauhan
Anjum Chauhan - avatar
4 odpowiedzi
+ 6
you can use the formula sum = n(n+1)/2 where n is the number of natural numbers you want to add. (it adds 1+2+3+4.....+n) To add numbers from x to n, you can use. sum = (n(n+1) - x(x+1)) / 2 EDIT: I didn't see that the previous post already covered it.
3rd Mar 2018, 4:10 AM
Tejaswi Hegde
Tejaswi Hegde - avatar
+ 2
If it's just within a range, you can easily use Gauss' formula to solve it. Here's a reference: https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/
3rd Mar 2018, 3:50 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar
+ 1
I am talking about sequence where we have a starting number and an ending number. e.g. sum of number between 5 & 50.
3rd Mar 2018, 3:16 AM
Anjum Chauhan
Anjum Chauhan - avatar
+ 1
@Jan Markus, quite correct, but there's still implicit loop in it.
3rd Mar 2018, 3:52 AM
Jonathan Pizarra (JS Challenger)
Jonathan Pizarra (JS Challenger) - avatar