Triangular Numbers | Python3 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
import math NEW_LINE def isTriangular ( num ) : NEW_LINE INDENT if ( num < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT c = ( - 2 * num ) NEW_LINE b , a = 1 , 1 NEW_LINE d = ( b * b ) - ( 4 * a * c ) NEW_LINE if ( d < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT root1 = ( - b + math . sqrt ( d ) ) / ( 2 * a ) NEW_LINE root2 = ( - b - math . sqrt ( d ) ) / ( 2 * a ) NEW_LINE if ( root1 > 0 and math . floor ( root1 ) == root1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root2 > 0 and math . floor ( root2 ) == root2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT n = 55 NEW_LINE if ( isTriangular ( n ) ) : NEW_LINE INDENT print ( " The ▁ number ▁ is ▁ a ▁ triangular ▁ number " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ number ▁ is ▁ NOT ▁ a ▁ triangular ▁ number " ) NEW_LINE DEDENT