![]() |
VOOZH | about |
Given a number n, find sum of first n odd natural numbers.
Input : 2 Output : 28 1^3 + 3^3 = 28 Input : 4 Output : 496 1^3 + 3^3 + 5^3 + 7^3 = 496
A simple solution is to traverse through n odd numbers and find the sum of cubes.
Output :
28
Time Complexity: O(n), as we are using a single traversal in the cubeSum() function.
Space Complexity:O(1)
An efficient solution is to apply the below formula.
sum = n2(2n2 - 1) How does it work? We know that sum of cubes of first n natural numbers is = n2(n+1)2 / 4 Sum of first n even numbers is 2 * n2(n+1)2 Sum of cubes of first n odd natural numbers = Sum of cubes of first 2n natural numbers - Sum of cubes of first n even natural numbers = (2n)2(2n+1)2 / 4 - 2 * n2(n+1)2 = n2(2n+1)2 - 2 * n2(n+1)2 = n2[(2n+1)2 - 2*(n+1)2] = n2(2n2 - 1)
Output:
496
Time Complexity: O(1)
Space Complexity: O(1)