Check if a number can be represented as a sum of 2 triangular numbers | C ++ implementation of the above 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkTriangularSumRepresentation ( int n ) { unordered_set < int > tri ; int i = 1 ; while ( 1 ) { int x = i * ( i + 1 ) / 2 ; if ( x >= n ) break ; tri . insert ( x ) ; i ++ ; } for ( auto tm : tri ) if ( tri . find ( n - tm ) != tri . end ( ) ) return true ; return false ; } int main ( ) { int n = 24 ; checkTriangularSumRepresentation ( n ) ? cout << " Yes " : cout << " No " ; return 0 ; }