How to find the nth Magic Number?
Wed Dec 25 2019 13:48:42 GMT+0000 (UTC)
Saved by
@marshmellow
#php
#interviewquestions
#makethisbetter
<?php
// PHP program to find nth
// magic number
// Function to find nth
// magic number
function nthMagicNo($n)
{
$pow = 1;
$answer = 0;
// Go through every bit of n
while ($n)
{
$pow = $pow * 5;
// If last bit of n is set
if ($n & 1)
$answer += $pow;
// proceed to next bit
$n >>= 1; // or $n = $n/2
}
return $answer;
}
// Driver Code
$n = 5;
echo "nth magic number is ",
nthMagicNo($n), "\n";
// This code is contributed by Ajit.
?>
content_copyCOPY
A magic number is defined as a number which can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), ….
This is how to write a function that finds the nth Magic number.
https://www.geeksforgeeks.org/find-nth-magic-number/
Comments
@logicloss01 - Thu Dec 26 2019 19:04:38 GMT+0000 (UTC)Thanks.. needed this for a paper!