text: Find all numbers up to N which are both Pentagonal and Hexagonal | Java program of the above approach ; Function to print numbers upto N which are both pentagonal as well as hexagonal numbers ; Calculate i - th pentagonal number ; Check if the pentagonal number pn is hexagonal or not ; Driver code
code: 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 ) ; } }