Check if a number can be represented as a sum of 2 triangular numbers | Java implementation of the approach ; Function to check if it is possible or not ; Store all triangular numbers up to N in a Set ; Check if a pair exists ; Driver code
import java . util . * ; class GFG { static boolean checkTriangularSumRepresentation ( int n ) { HashSet < Integer > tri = new HashSet < > ( ) ; int i = 1 ; while ( true ) { int x = i * ( i + 1 ) / 2 ; if ( x >= n ) { break ; } tri . add ( x ) ; i ++ ; } for ( Integer tm : tri ) { if ( tri . contains ( n - tm ) && ( n - tm ) != ( int ) tri . toArray ( ) [ tri . size ( ) - 1 ] ) { return true ; } } return false ; } public static void main ( String [ ] args ) { int n = 24 ; if ( checkTriangularSumRepresentation ( n ) ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } }