Skip to content

Instantly share code, notes, and snippets.

@mmloveaa
Last active March 8, 2017 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmloveaa/71143f11ab89944d1dea to your computer and use it in GitHub Desktop.
Save mmloveaa/71143f11ab89944d1dea to your computer and use it in GitHub Desktop.
Triangle sum of odd numbers
// 1/10/2016 (Great Question*)
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
// 1
// 3 5, 2*1 + 1 row 2 * 1
// 7 9 11, 2*3 + 1 row 3 * 3
// 13 15 17 19, 2*6 + 1 row 4 * 6
// 21 23 25 27 29, 2*10 + 1 row 5 * 10
// 31 33 35 37 39 41, 2*15 + 1
// 1 1-1
// 2 2-3
// 3 4-6
// 4 7-10
// 5 11-15
// 6 16-21
// 6) 15 = 1+2+3+4+5
// 5) 10 = 1+2+3+4
// 4) 6 = 1+2+3
// 3) 3=1+2
// 2) 1=1
// 1) 0
My Solution:
function addRow(n) {
var total=0;
for (var i=0;i<n;i++){
total+=i
// console.log(total)
}
var firstNum=2*total+1
// console.log(firstNum)
var sum=0;
for (j=0;j<n;j++){
sum+=firstNum
firstNum+=2
console.log('in loop ', sum)
}
return sum
}
addRow(42)
@wot48
Copy link

wot48 commented Mar 8, 2017

return n*n*n

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment