I have attempted to make a piece of code that accepts an input of "n", calculates the sum of the numbers on the nth line an odd number triangle, which looks like:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
etc. So for n = 3
, the sum would be 7 + 9 + 11
ie 27
I know that n is not only the line number but also equals the number of numbers on that line. so n = 3
also have 3 odd numbers on it. Therefore I thought that I could get the first number of the line, then just loop through adding two to the previous number then sum it.
My code below doesn't work, so for an input of n=43
, my code calculates that the sum is 3570
whereas it actually equals 79507
.
public static int rowSumOddNumbers(int n) {
int firstNum = (2 * n) - 1;
int total = 0;
for (int i = 0; i < n; i++) {
total += (firstNum + 2);
}
return total;
}
I believe my problem is that I'm not adding the previous number together with the current number + 2. Should it be that I need to store the previous loop's outcome than add it to the current loop's outcome?
Any help appreciated.
The total of any set of sequential odd numbers beginning with 1 is always equal to the square of the number of digits, added together. If 1,3,5,7,9,11,…, (2n-1) are the odd numbers, then; Sum of first odd number = 1. Sum of first two odd numbers = 1 + 3 = 4 (4 = 2 x 2).
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With