Program to check if N is a Centered Triangular Number
Given an integer N, the task is to check if it is a Centered triangular number or not.
Centered triangular number is a centered polygonal number that represents a triangle with a dot in the centre and all other dots surrounding the centre in successive triangular layers . The first few Centered triangular numbers are 1, 4, 10, 19, 31, 46, 64, 85, 109, 136, …
Examples:
Input: N = 4
Output: Yes
Input: 20
Output: No
Approach:
- The Kth Centered triangular number can be expressed as:
- In order to check if the given number N can be expressed as a Centered triangular number or not, we need to check if gives an integer or not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isCenteredtriangular( int N)
{
float K = (-3
+ sqrt (24 * N - 15))
/ 6;
return (K - ( int )K) == 0;
}
int main()
{
int N = 85;
if (isCenteredtriangular(N)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
import java.lang.Math;
class GFG{
public static boolean isCenteredTriangular( int N)
{
double K = (- 3 + Math.sqrt( 24 * N - 15 )) / 6 ;
return (K - ( int )K) == 0 ;
}
public static void main(String[] args)
{
int N = 85 ;
if (isCenteredTriangular(N))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
import math
def isCenteredtriangular(N):
K = ( - 3 + math.sqrt( 24 * N - 15 )) / 6
if (K - int (K)) = = 0 :
return True
return False
N = 85
if (isCenteredtriangular(N)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool isCenteredtriangular( int N)
{
double K = (-3 + Math.Sqrt(24 * N - 15)) / 6;
return (K - ( int )K) == 0;
}
static public void Main ()
{
int N = 85;
if (isCenteredtriangular(N))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function isCenteredtriangular(N)
{
var K = (-3
+ Math.sqrt(24 * N - 15))
/ 6;
return (K - parseInt(K)) == 0;
}
var N = 85;
if (isCenteredtriangular(N)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
</script>
|
Time Complexity: O(logN) because inbuilt sqrt function is being used
Auxiliary Space: O(1)
Last Updated :
19 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...