坎宁安数是以下形式的数字N ,其中a,b> = 2。
坎宁安(Cunningham)的数字很少:
3, 5, 7, 8, 9, 10, 15, 17, 24, 26, 28…
检查N是否为坎宁安数
给定数字N ,任务是检查N是否为坎宁安数字。如果N是坎宁安数,则打印“是”,否则打印“否” 。
例子:
Input: N = 126
Output: Yes
Explanation:
126 = 5^3+1
Input: N = 16
Output: No
方法:想法是以所需的形式求解方程,以便检查该数字是否为Cunningham数字很容易。
//坎宁安数字是// //可以表示为=> =>
因此,如果或者可以以 ,则数字为坎宁安数字。
下面是上述方法的实现:
C++
// C++ implementation for the
// above approach
#include
using namespace std;
// Function to check if a number
// can be expressed as a^b.
bool isPower(int a)
{
if (a == 1)
return true;
for (int i = 2; i * i <= a; i++) {
double val = log(a) / log(i);
if ((val - (int)val) < 0.00000001)
return true;
}
return false;
}
// Function to check if N is a
// Cunningham number
bool isCunningham(int n)
{
return isPower(n - 1) ||
isPower(n + 1);
}
// Driver Code
int main()
{
// Given Number
int n = 126;
// Function Call
if (isCunningham(n))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation for the above approach
import java.util.*;
class GFG{
// Function to check if a number
// can be expressed as a^b.
static boolean isPower(int a)
{
if (a == 1)
return true;
for(int i = 2; i * i <= a; i++)
{
double val = Math.log(a) / Math.log(i);
if ((val - (int)val) < 0.00000001)
return true;
}
return false;
}
// Function to check if N is a
// Cunningham number
static boolean isCunningham(int n)
{
return isPower(n - 1) ||
isPower(n + 1);
}
// Driver Code
public static void main (String[] args)
{
// Given Number
int n = 126;
// Function Call
if (isCunningham(n))
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by Ritik Bansal
Python3
# Python3 implementation for the
# above approach
import math
# Function to check if a number
# can be expressed as a^b.
def isPower(a):
if (a == 1):
return True
i = 2
while(i * i <= a):
val = math.log(a) / math.log(i)
if ((val - int(val)) < 0.00000001):
return True
i += 1
return False
# Function to check if N is a
# Cunningham number
def isCunningham(n):
return isPower(n - 1) or isPower(n + 1)
# Driver Code
# Given Number
n = 126
# Function Call
if (isCunningham(n)):
print("Yes")
else:
print("No")
# This code is contributed by shubhamsingh10
C#
// C# implementation for the
// above approach
using System;
class GFG{
// Function to check if a number
// can be expressed as a^b.
static bool isPower(int a)
{
if (a == 1)
return true;
for(int i = 2; i * i <= a; i++)
{
double val = Math.Log(a) / Math.Log(i);
if ((val - (int)val) < 0.00000001)
return true;
}
return false;
}
// Function to check if N is a
// Cunningham number
static bool isCunningham(int n)
{
return isPower(n - 1) ||
isPower(n + 1);
}
// Driver Code
public static void Main (string[] args)
{
// Given number
int n = 126;
// Function Call
if (isCunningham(n))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by rock_cool
Javascript
输出:
Yes
参考: https : //oeis.org/A080262