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), ….
Write a function to find the nth Magic number.
Example:
Input: n = 2
Output: 25
Input: n = 5
Output: 130
If we notice carefully the magic numbers can be represented as 001, 010, 011, 100, 101, 110 etc, where 001 is 0*pow(5,3) + 0*pow(5,2) + 1*pow(5,1). So basically we need to add powers of 5 for each bit set in a given integer n.
Below is the implementation based on this idea.
Approach :
Step 1 : declare and assign a number for which you want to find the magic number.
Step 2 : assign a pow = 1, and ans = 0
Step 3 : use while loop to iterate each bit until ends (while n > 0)
Step 4 : inside loop, find last bit using & operation and keep updating answer and power as well
Step 5 : Once loop exit return answer
C++
#include <bits/stdc++.h>
using namespace std;
int nthMagicNo( int n)
{
int pow = 1, answer = 0;
while (n)
{
pow = pow *5;
if (n & 1)
answer += pow ;
n >>= 1;
}
return answer;
}
int main()
{
int n = 5;
cout << "nth magic number is " << nthMagicNo(n) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int nthMagicNo( int n)
{
int pow = 1 , answer = 0 ;
while (n != 0 )
{
pow = pow* 5 ;
if (( int )(n & 1 ) == 1 )
answer += pow;
n >>= 1 ;
}
return answer;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.println( "nth magic" +
" number is " + nthMagicNo(n));
}
}
|
Python3
def nthMagicNo(n):
pow = 1
answer = 0
while (n):
pow = pow * 5
if (n & 1 ):
answer + = pow
n >> = 1
return answer
n = 5
print ( "nth magic number is" , nthMagicNo(n))
|
C#
using System;
public class GFG
{
static int nthMagicNo( int n)
{
int pow = 1, answer = 0;
while (n != 0)
{
pow = pow * 5;
if (( int )(n & 1) == 1)
answer += pow;
n >>= 1;
}
return answer;
}
public static void Main()
{
int n = 5;
Console.WriteLine( "nth magic" + " number is "
+ nthMagicNo(n));
}
}
|
PHP
<?php
function nthMagicNo( $n )
{
$pow = 1;
$answer = 0;
while ( $n )
{
$pow = $pow * 5;
if ( $n & 1)
$answer += $pow ;
$n >>= 1;
}
return $answer ;
}
$n = 5;
echo "nth magic number is " ,
nthMagicNo( $n ), "\n" ;
?>
|
Javascript
<script>
function nthMagicNo(n)
{
let pow = 1, answer = 0;
while (n != 0)
{
pow = pow * 5;
if ((n & 1) == 1)
answer += pow;
n >>= 1;
}
return answer;
}
let n = 5;
document.write( "nth magic" + " number is " + nthMagicNo(n));
</script>
|
Output :
nth magic number is 130
Complexity :
Time complexity : O(logN)
Auxiliary Space : O(1)
Thanks to manrajsingh for suggesting the above solution.
This article is contributed by Abhay. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.