Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

# Is this the most efficient solution for taking the sum?

Ranch Hand
Posts: 63
Here are two methods, iterative and recursive, which calculates the sum of all positive integers between 1 and a given integer n (input into the method). We know that as n gets larger, the solution takes longer to solve. Is there you think a much more efficient way of writing these codes?

NOTE: I'VE CROSS POST HERE Is this the most efficient solution for taking the sum?
I'll let everyone know whether my answer is resolved from the other forum so I don't waste anybody's time. Thanks!

Iterative Method:

Recursive Method:

author & internet detective
Posts: 40200
816

Note this isn't the standard idiom in Java. It is traditional to increment i rather than decrement n.

And I agree with the poster in your cross post about int sum = (n*(n+1))/2; being more efficient. I learned about that through puzzles in elementary school so it definitely isn't something the person made up on the spot.

Aron Silvester
Ranch Hand
Posts: 63

Jeanne Boyarsky wrote:
Note this isn't the standard idiom in Java. It is traditional to increment i rather than decrement n.

And I agree with the poster in your cross post about int sum = (n*(n+1))/2; being more efficient. I learned about that through puzzles in elementary school so it definitely isn't something the person made up on the spot.

Alright I changed it.

Bartender
Posts: 612
7
As was already stated - the most efficient is not a for loop (that was noted as you were using non-standard syntax) but the equation sum = (x * (x + 1 )) /2

loops takes O(n) while the equation takes O(c)

Note when you fully understand this, you will realize the there is one boundary condition that the equation does not work the the loop works - but that can be easily corrected.

 Let nothing stop you! Not even this tiny ad: Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton