CodeWars - Sum of odd Numbers - For loop
Mathematically, the sum of the nth line of odd numbers is n3, so this gives the correct result:
int rowSumOddNumbers(int n) {
return n * n * n;
}
I leave the derivation to the reader...
for javascript this would be simply
Math.pow(n,3)
This is how you can approach the problem there may other faster methods also.First you have to find the first number in the nth line.You can see that the starting numbers of every line are in a sequence (arithmetic progress - AP)
1 3 7 13 21 ...
therefore nth term will be (n-1)^2 + (n-1)+1
Once you find that,you can find the sum of all the digits in that line by iterating from that number to the number of terms in the line
for(int i=0;i<n;i+=2)
{
sum+=(Nth_Term+i);
}
or simply just apply the formula of the sum of n-terms of AP with comman ratio 2
sum= n*( 2*Nth_Term + (n-1)*2)/2 ;
Further if you will put the value of Nth term in the above formula you will find that it evaluates to n^3.
sum = n*( 2* ((n-1)^2 + (n-1)+1) + (n-1)*2)/2 = n^3
int rowSumOddNumbers(int n) {
var odd = [];
var starts = (n * n) - (n - 1);
while(n > 0){
odd.add(starts);
starts += 2;
n--;
}
int sum = odd.reduce((value, element) => value + element);
print(sum);
return sum;
}