给定整数N ,任务是检查N是否为七边形数。如果数字N是七边形数字,则打印“是”,否则打印“否” 。
Heptagonal Number represents Heptagon and belongs to a figurative number. Heptagonal has seven angles, seven vertices, and seven-sided polygon. The first few Heptagonal Numbers are 1, 7, 18, 34, 55, 81, …
例子:
Input: N = 7
Output: Yes
Explanation:
Second heptagonal number is 7.
Input: N = 30
Output: No
方法:
- 七边形数的第K个项为
- 因为我们必须检查给定的数字是否可以表示为七边形数字。可以检查为:
=>
=>
- 如果使用上述公式计算出的K的值为整数,则N为七边形数。
- 其他N不是七边形数字。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if N is a
// Heptagonal number
bool isheptagonal(int N)
{
float n
= (3 + sqrt(40 * N + 9))
/ 10;
// Condition to check if the
// number is a heptagonal number
return (n - (int)n) == 0;
}
// Driver Code
int main()
{
// Given Nuber
int N = 7;
// Function call
if (isheptagonal(N)) {
cout << "Yes";
}
else {
cout << "No";
}
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to check if N
// is a heptagonal number
public static boolean isheptagonal(int N)
{
double n = (3 + Math.sqrt(40 * N + 9)) / 10;
// Condition to check if the number
// is a heptagonal number
return (n - (int)n) == 0;
}
// Driver code
public static void main(String[] args)
{
// Given Number
int N = 7;
// Function call
if (isheptagonal(N))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
// This code is contributed by coder001
Python3
# Python3 program for the above approach
import math
# Function to check if N is a
# heptagonal number
def isheptagonal(N):
n = (3 + math.sqrt(40 * N + 9)) / 10
# Condition to check if the
# number is a heptagonal number
return (n - int(n)) == 0
# Driver Code
N = 7
# Function call
if (isheptagonal(N)):
print("Yes")
else:
print("No")
# This code is contributed by Shubham_Coder
C#
// C# program for the above approach
using System;
class GFG {
// Function to check if N
// is a heptagonal number
public static bool isheptagonal(int N)
{
double n = (3 + Math.Sqrt(40 * N + 9)) / 10;
// Condition to check if the number
// is a heptagonal number
return (n - (int)n) == 0;
}
// Driver code
public static void Main(String[] args)
{
// Given Number
int N = 7;
// Function call
if (isheptagonal(N))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
// This code is contributed by Rohit_ranjan
Javascript
输出:
Yes
时间复杂度: O(1)
辅助空间: O(1)