魔数定义为一个数字,可以表示为5的幂或5的唯一幂的总和。前几个幻数为5、25、30(5 + 25),125、130(125 + 5), …。
编写函数以查找第n个幻数。
例子:
Input: n = 2
Output: 25
Input: n = 5
Output: 130
如果我们仔细注意魔术数字可以表示为001、010、011、100、101、110等,其中001是0 * pow(5,3)+ 0 * pow(5,2)+ 1 * pow(5 ,1)。因此,基本上,我们需要为给定整数n中的每个位加5的幂。
以下是基于此思想的实现。
C++
// C++ program to find nth magic numebr
#include
using namespace std;
// Function to find nth magic numebr
int nthMagicNo(int n)
{
int 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 program to test above function
int main()
{
int n = 5;
cout << "nth magic number is " << nthMagicNo(n) << endl;
return 0;
}
Java
// Java program to find nth
// magic numebr
import java.io.*;
class GFG
{
// Function to find nth magic number
static int nthMagicNo(int n)
{
int pow = 1, answer = 0;
// Go through every bit of n
while (n != 0)
{
pow = pow*5;
// If last bit of n is set
if ((int)(n & 1) == 1)
answer += pow;
// proceed to next bit
// or n = n/2
n >>= 1;
}
return answer;
}
// Driver program to test
// above function
public static void main(String[] args)
{
int n = 5;
System.out.println("nth magic" +
" number is " + nthMagicNo(n));
}
}
// This code is contributed by
// prerna saini
Python3
# Python program to find nth magic numebr
# Function to find nth magic numebr
def 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 program to test above function
n = 5
print("nth magic number is", nthMagicNo(n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to find nth
// magic numebr
using System;
public class GFG
{
// Function to find nth magic number
static int nthMagicNo(int n)
{
int pow = 1, answer = 0;
// Go through every bit of n
while (n != 0)
{
pow = pow * 5;
// If last bit of n is set
if ((int)(n & 1) == 1)
answer += pow;
// proceed to next bit
// or n = n/2
n >>= 1;
}
return answer;
}
// Driver Code
public static void Main()
{
int n = 5;
Console.WriteLine("nth magic" + " number is "
+ nthMagicNo(n));
}
}
// This code is contributed by Sam007
PHP
>= 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.
?>
Javascript
输出 :
nth magic number is 130
感谢manrajsingh提出上述解决方案。