Triangular Numbers | C ++ program to check if a number is a triangular number using quadratic equation . ; Returns true if num is triangular ; Considering the equation n * ( n + 1 ) / 2 = num The equation is : a ( n ^ 2 ) + bn + c = 0 "; ; Find roots of equation ; checking if root1 is natural ; checking if root2 is natural ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isTriangular ( int num ) { if ( num < 0 ) return false ; int c = ( -2 * num ) ; int b = 1 , a = 1 ; int d = ( b * b ) - ( 4 * a * c ) ; if ( d < 0 ) return false ; float root1 = ( - b + sqrt ( d ) ) / ( 2 * a ) ; float root2 = ( - b - sqrt ( d ) ) / ( 2 * a ) ; if ( root1 > 0 && floor ( root1 ) == root1 ) return true ; if ( root2 > 0 && floor ( root2 ) == root2 ) return true ; return false ; } int main ( ) { int num = 55 ; if ( isTriangular ( num ) ) cout << " The ▁ number ▁ is ▁ a ▁ triangular ▁ number " ; else cout << " The ▁ number ▁ is ▁ NOT ▁ a ▁ triangular ▁ number " ; return 0 ; }