Find all numbers up to N which are both Pentagonal and Hexagonal
Last Updated :
11 Nov, 2021
Given an integer N, the task is to find all numbers up to N, which are both Pentagonal as well as Hexagonal.
Example:
Input: N = 1000
Output: 1
Input: N = 100000
Output: 1, 40755
Approach:
- To solve the problem, we are generating all pentagonal numbers up to N and check if those are hexagonal numbers or not.
- Formula to calculate ith Pentagonal Number:
i * ( 3 * i – 1 ) / 2
- To check if a pentagonal number, say pn, is a hexagonal number or not:
( 1 + sqrt(8 * pn + 1 ) ) / 4 needs to be a Natural number
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void pen_hex( long long n)
{
long long pn = 1;
for ( long long int i = 1;; i++) {
pn = i * (3 * i - 1) / 2;
if (pn > n)
break ;
long double seqNum
= (1 + sqrt (8 * pn + 1)) / 4;
if (seqNum == long (seqNum))
cout << pn << ", " ;
}
}
int main()
{
long long int N = 1000000;
pen_hex(N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void pen_hex( long n)
{
long pn = 1 ;
for ( long i = 1 ; i < n; i++)
{
pn = i * ( 3 * i - 1 ) / 2 ;
if (pn > n)
break ;
double seqNum = ( 1 + Math.sqrt(
8 * pn + 1 )) / 4 ;
if (seqNum == ( long )seqNum)
System.out.print(pn + ", " );
}
}
public static void main(String[] args)
{
long N = 1000000 ;
pen_hex(N);
}
}
|
Python3
import math
def pen_hex(n):
pn = 1
for i in range ( 1 , N):
pn = ( int )(i * ( 3 * i - 1 ) / 2 )
if (pn > n):
break
seqNum = ( 1 + math.sqrt( 8 * pn + 1 )) / 4
if (seqNum = = ( int )(seqNum)):
print (pn, end = ", " )
N = 1000000
pen_hex(N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void pen_hex( long n)
{
long pn = 1;
for ( long i = 1;; i++)
{
pn = i * (3 * i - 1) / 2;
if (pn > n)
break ;
double seqNum = (1 + Math.Sqrt(
8 * pn + 1)) / 4;
if (seqNum == ( long )(seqNum))
{
Console.Write(pn + ", " );
}
}
}
public static void Main ( string [] args)
{
long N = 1000000;
pen_hex(N);
}
}
|
Javascript
<script>
function pen_hex(n)
{
var pn = 1;
for (i = 1; i < n; i++)
{
pn = parseInt(i * (3 * i - 1) / 2);
if (pn > n)
break ;
var seqNum = (1 + Math.sqrt(
8 * pn + 1)) / 4;
if (seqNum == parseInt(seqNum))
document.write(pn + ", " );
}
}
var N = 1000000;
pen_hex(N);
</script>
|
Time Complexity: O(N)
Auxiliary space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...