给定数字N ,任务是检查N是否为八角形数。如果数字N是八角形数字,则打印“是”,否则打印“否” 。
Octagonal Number is the figure number that represent octagonal. Octagonal Numbers can be formed by placing triangular numbers on the four sides of a square. The first few Octagonal Numbers are 1, 8, 21, 40, 65, 96 …
例子:
Input: N = 8
Output: Yes
Explanation:
Second octagonal number is 8.
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
// Octagonal Number
bool isoctagonal(int N)
{
float n
= (2 + sqrt(12 * N + 4))
/ 6;
// Condition to check if the
// number is a octagonal number
return (n - (int)n) == 0;
}
// Driver Code
int main()
{
// Given Number
int N = 8;
// Function call
if (isoctagonal(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
// octagonal number
public static boolean isoctagonal(int N)
{
double n = (2 + Math.sqrt(12 * N + 4)) / 6;
// Condition to check if the
// number is a octagonal number
return (n - (int)n) == 0;
}
// Driver code
public static void main(String[] args)
{
// Given Number
int N = 8;
// Function call
if (isoctagonal(N))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
// This code is contributed by coder001
Python3
# Python3 program for the above approach
from math import sqrt
# Function to check if N is a
# octagonal number
def isoctagonal(N):
n = (2 + sqrt(12 * N + 4)) / 6;
# Condition to check if the
# number is a octagonal number
return (n - int(n)) == 0;
# Driver Code
if __name__ == "__main__":
# Given number
N = 8;
# Function call
if (isoctagonal(N)):
print("Yes");
else:
print("No");
# This code is contributed by AnkitRai01
C#
// C# program for the above approach
using System;
class GFG {
// Function to check if N is a
// octagonal number
public static bool isoctagonal(int N)
{
double n = (2 + Math.Sqrt(12 * N +
4)) / 6;
// Condition to check if the
// number is a octagonal number
return (n - (int)n) == 0;
}
// Driver code
public static void Main(String[] args)
{
// Given number
int N = 8;
// Function call
if (isoctagonal(N))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
// This code is contributed by Rohit_ranjan
Javascript
输出:
Yes