posted 2 years ago
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:
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:
posted 2 years ago
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.
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.
[OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Aron Silvester
Ranch Hand
Posts: 63
posted 2 years ago
Alright I changed it.
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.
posted 2 years ago
As was already stated  the most efficient is not a for loop (that was noted as you were using nonstandard 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.
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.
Get off me! Here, read this tiny ad:
The WEB SERVICES and JAXRS Course
https://coderanch.com/t/690789/WEBSERVICESJAXRS
