给定整数N ,任务是检查它是否是居中八角形数。如果数字N是居中八角形数字,则打印“是”,否则打印“否” 。
Centered Octagonal number represents an octagon with a dot in the centre and others dots surrounding the centre dot in the successive octagonal layer.The first few Centered Octagonal numbers are 1, 9, 25, 49, 81, 121, 169, 225, 289, 361 …
例子:
Input: N = 9
Output: Yes
Explanation:
Second Centered Octagonal number is 9.
Input: 16
Output: No
方法:
1.中心八角形数的第K个项为
2.由于我们必须检查给定的数字是否可以表示为中心八角形数。可以按以下方式检查–
=>
=>
3.如果使用上述公式计算出的K的值为整数,则N为中心八角形数。
4.其他N不是中心八角形数。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check if the number N
// is a Centered Octagonal number
bool isCenteredOctagonal(int N)
{
float n
= (1 + sqrt(N))
/ 2;
// Condition to check if the number
// is a Centered Octagonal number
return (n - (int)n) == 0;
}
// Driver Code
int main()
{
// Given Number
int N = 9;
// Function call
if (isCenteredOctagonal(N)) {
cout << "Yes";
}
else {
cout << "No";
}
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to check if the number N
// is a centered octagonal number
static boolean isCenteredOctagonal(int N)
{
float n = (float) ((1 + Math.sqrt(N)) / 2);
// Condition to check if the number
// is a centered octagonal number
return (n - (int)n) == 0;
}
// Driver Code
public static void main(String[] args)
{
// Given Number
int N = 9;
// Function call
if (isCenteredOctagonal(N))
{
System.out.print("Yes");
}
else
{
System.out.print("No");
}
}
}
// This code is contributed by sapnasingh4991
Python3
# Python3 program for the above approach
import numpy as np
# Function to check if the number N
# is a centered octagonal number
def isCenteredOctagonal(N):
n = (1 + np.sqrt(N)) / 2
# Condition to check if N
# is a centered octagonal number
return (n - int(n)) == 0
# Driver Code
N = 9
# Function call
if (isCenteredOctagonal(N)):
print("Yes")
else:
print("No")
# This code is contributed by PratikBasu
C#
// C# program for the above approach
using System;
class GFG{
// Function to check if the number N
// is a centered octagonal number
static bool isCenteredOctagonal(int N)
{
float n = (float) ((1 + Math.Sqrt(N)) / 2);
// Condition to check if the number
// is a centered octagonal number
return (n - (int)n) == 0;
}
// Driver Code
public static void Main(string[] args)
{
// Given Number
int N = 9;
// Function call
if (isCenteredOctagonal(N))
{
Console.Write("Yes");
}
else
{
Console.Write("No");
}
}
}
// This code is contributed by rutvik_56
Javascript
输出:
Yes
时间复杂度: O(1)
辅助空间: O(1)