I don’t understand why my code doesn’t work.
Here is the instructions about the problem:
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
Calculate the sum of the numbers in the nth row of this triangle (starting at index 1) e.g.: (Input –> Output)
1 --> 1
2 --> 3 + 5 = 8
Bellow is my code written to the PHP:
function rowSumOddNumbers($n) {
if ($n==1){
return 1;
}
$licznik = 0;
for ($i=$n; $i>0; $i--){
$licznik += $i;
}
$liczba = ($licznik*$n) - 1;
$suma = 0;
for ($i=$n; $i>0; $i--){
$suma += $liczba;
$liczba = $liczba - 2;
}
return $suma;
}
The testcase which broke my code was:
Failed asserting that 15210 is identical to 2197.
I don’t want to know what code will make this fine, but a clue why mine doesn’t work. Please help
I tried to calculate how my code react and it seems fine.
2