• Post Reply Bookmark Topic Watch Topic
  • New Topic

Is this the most efficient solution for taking the sum?  RSS feed

 
Aron Silvester
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37253
519
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Steve Fahlbusch
Bartender
Posts: 612
7
Mac OS X Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!