给定整数N ,任务是检查N是否为同心六边形。如果数字N是同心六边形,则打印“是”,否则打印“否” 。
Concentric Hexagonal Numbers are the number sequence forms a pattern with concentric hexagons, and the numbers denote the number of points required after the N-th stage of the pattern. The first few concentric hexagonal numbers are 0, 1, 6, 13, 24, 37, 54, 73, 96, 121 …
例子:
Input: N = 6
Output: Yes
Explanation:
Third Concentrichexagonal number is 6.
Input: N = 20
Output: No
方法:
- 同心六角形数的第K个项为:
Kth Term = (3 * K * K) / 2
- 因为我们必须检查给定的数字是否可以表示为同心六角形数字。可以检查为:
Here, Kth Term = N
=> (3 * K * K) / 2 = N
=> 3 * K * K – 2 * N = 0
The positive root of this equation is:
K = sqrt((2 * N )/3) - 如果使用上述公式计算出的K值为整数,则N为同心六边形数。
- 否则,数字N不是同心六边形。
下面是上述方法的实现:
C++
// C++ program to check if N is a // Concentric Hexagonal Number #include
using namespace std; // Function to check if the // number is a Concentric hexagonal number bool isConcentrichexagonal(int N) { float n = sqrt((2 * N) / 3); // Condition to check if the // number is a Concentric // hexagonal number return (n - (int)n) == 0; } // Driver Code int main() { int N = 6; // Function call if (isConcentrichexagonal(N)) { cout << "Yes"; } else { cout << "No"; } return 0; }
Java
// Java program to check if N is a // Concentric Hexagonal Number class GFG{ // Function to check if the // number is a Concentric hexagonal number static boolean isConcentrichexagonal(int N) { float n = (float) Math.sqrt((2 * N) / 3); // Condition to check if the // number is a Concentric // hexagonal number return (n - (int)n) == 0; } // Driver Code public static void main(String[] args) { int N = 6; // Function call if (isConcentrichexagonal(N)) { System.out.print("Yes"); } else { System.out.print("No"); } } } // This code is contributed by PrinciRaj1992
Python3
# Python3 program to check if N is a # concentric hexagonal number import math # Function to check if the number # is a concentric hexagonal number def isConcentrichexagonal(N): n = math.sqrt((2 * N) / 3) # Condition to check if the # number is a concentric # hexagonal number return (n - int(n)) == 0 # Driver code N = 6 if isConcentrichexagonal(N): print("Yes") else: print("No") # This code is contributed by divyeshrabadiya07
C#
// C# program to check if N is a // concentric hexagonal number using System; class GFG{ // Function to check if the number // is a concentric hexagonal number static bool isConcentrichexagonal(int N) { float n = (float) Math.Sqrt((2 * N) / 3); // Condition to check if the // number is a concentric // hexagonal number return (n - (int)n) == 0; } // Driver Code public static void Main() { int N = 6; // Function call if (isConcentrichexagonal(N)) { Console.Write("Yes"); } else { Console.Write("No"); } } } // This code is contributed by Code_Mech
输出:Yes