find the nth octagonal number in php

To find the nth octagonal number, you can use the formula:

main.php
$octagonal_number = 3*$n*($n-1)+1;
35 chars
2 lines

where $n is the index of the octagonal number.

Alternatively, you can use a loop to generate the octagonal numbers up to the nth index:

main.php
function get_octagonal_number($n) {
    if($n <= 0) {
        return 0;
    }
    return 3*$n*($n-1)+1;
}

function get_nth_octagonal_number($n) {
    for($i = 1; $i <= $n; $i++) {
        $octagonal_number = get_octagonal_number($i);
    }
    return $octagonal_number;
}
273 chars
14 lines

This function generates octagonal numbers up to the nth index and returns the nth octagonal number.

You can call the function by passing the index of the desired octagonal number:

main.php
echo get_nth_octagonal_number(5); // outputs 141
49 chars
2 lines

In this case, the output is 141, which is the 5th octagonal number.

gistlibby LogSnag