Un número se denomina número triangular si podemos representarlo en forma de rejilla triangular de puntos tal que los puntos formen un triángulo equilátero y cada fila contenga tantos puntos como el número de la fila, es decir, la primera fila tiene un punto, la segunda la fila tiene dos puntos, la tercera fila tiene tres puntos y así sucesivamente. Los números triangulares iniciales son 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4).
¿Cómo comprobar si un número es triangular?
La idea se basa en el hecho de que el n-ésimo número triangular se puede escribir como la suma de n números naturales, es decir, n*(n+1)/2. La razón de esto es simple, la línea base de la cuadrícula triangular tiene n puntos, la línea sobre la base tiene (n-1) puntos y así sucesivamente.
Método 1 (Simple)
Comenzamos con 1 y verificamos si el número es igual a 1. Si no lo es, sumamos 2 para convertirlo en 3 y volvemos a verificar con el número. Repetimos este procedimiento hasta que la suma quede menor o igual que el número que se quiere comprobar que es triangular.
A continuación se muestran las implementaciones para verificar si un número es un número triangular.
C++
// C++ program to check if a number is a triangular number // using simple approach. #include <iostream> using namespace std; // Returns true if 'num' is triangular, else false bool isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be sum of first n // natural numbers int sum = 0; for (int n=1; sum<=num; n++) { sum = sum + n; if (sum==num) return true; } return false; } // Driver code int main() { int n = 55; if (isTriangular(n)) cout << "The number is a triangular number"; else cout << "The number is NOT a triangular number"; return 0; }
Java
// Java program to check if a // number is a triangular number // using simple approach class GFG { // Returns true if 'num' is // triangular, else false static boolean isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be // sum of first n natural numbers int sum = 0; for (int n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code public static void main (String[] args) { int n = 55; if (isTriangular(n)) System.out.print("The number " + "is a triangular number"); else System.out.print("The number" + " is NOT a triangular number"); } } // This code is contributed // by Anant Agarwal.
Python3
# Python3 program to check if a number is a # triangular number using simple approach. # Returns True if 'num' is triangular, else False def isTriangular(num): # Base case if (num < 0): return False # A Triangular number must be # sum of first n natural numbers sum, n = 0, 1 while(sum <= num): sum = sum + n if (sum == num): return True n += 1 return False # Driver code n = 55 if (isTriangular(n)): print("The number is a triangular number") else: print("The number is NOT a triangular number") # This code is contributed by Smitha Dinesh Semwal.
C#
// C# program to check if a number is a // triangular number using simple approach using System; class GFG { // Returns true if 'num' is // triangular, else false static bool isTriangular(int num) { // Base case if (num < 0) return false; // A Triangular number must be // sum of first n natural numbers int sum = 0; for (int n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code public static void Main () { int n = 55; if (isTriangular(n)) Console.WriteLine("The number " + "is a triangular number"); else Console.WriteLine("The number" + " is NOT a triangular number"); } } // This code is contributed by vt_m.
PHP
<?php // PHP program to check if a number is a // triangular number using simple approach. // Returns true if 'num' is triangular, // else false function isTriangular( $num) { // Base case if ($num < 0) return false; // A Triangular number must be // sum of first n natural numbers $sum = 0; for ($n = 1; $sum <= $num; $n++) { $sum = $sum + $n; if ($sum == $num) return true; } return false; } // Driver code $n = 55; if (isTriangular($n)) echo "The number is a triangular number"; else echo "The number is NOT a triangular number"; // This code is contributed by Rajput-Ji ?>
Javascript
<script> // javascript program to check if a number is a triangular number // using simple approach. // Returns true if 'num' is triangular, else false function isTriangular(num) { // Base case if (num < 0) return false; // A Triangular number must be sum of first n // natural numbers let sum = 0; for (let n = 1; sum <= num; n++) { sum = sum + n; if (sum == num) return true; } return false; } // Driver code let n = 55; if (isTriangular(n)) document.write( "The number is a triangular number"); else document.write( "The number is NOT a triangular number"); // This code is contributed by aashish1995 </script>
Producción:
The number is a triangular number
Complejidad de tiempo: O(n)
Espacio auxiliar: O(1)
Método 2 (Uso de la fórmula raíz de la ecuación cuadrática)
Formamos una ecuación cuadrática igualando el número a la fórmula de la suma de los primeros ‘n’ números naturales, y si obtenemos al menos un valor de ‘n’ que es un número natural, decimos que el número es un número triangular.
Let the input number be 'num'. We consider, n*(n+1) = num as, n2 + n + (-2 * num) = 0
A continuación se muestra la implementación de la idea anterior.
C++
// C++ program to check if a number is a triangular number // using quadratic equation. #include <bits/stdc++.h> using namespace std; // Returns true if num is triangular bool isTriangular(int num) { if (num < 0) return false; // Considering the equation n*(n+1)/2 = num // The equation is : a(n^2) + bn + c = 0"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + sqrt(d)) / (2 * a); float root2 = ( -b - sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && floor(root2) == root2) return true; return false; } // Driver code 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; }
Java
// Java program to check if a number is a // triangular number using quadratic equation. import java.io.*; class GFG { // Returns true if num is triangular static boolean isTriangular(int num) { if (num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + (float)Math.sqrt(d)) / (2 * a); float root2 = ( -b - (float)Math.sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.floor(root2) == root2) return true; return false; } // Driver code public static void main (String[] args) { int num = 55; if (isTriangular(num)) System.out.println("The number is" + " a triangular number"); else System.out.println ("The number " + "is NOT a triangular number"); } } //This code is contributed by vt_m.
Python3
# Python3 program to check if a number is a # triangular number using quadratic equation. import math # Returns True if num is triangular def isTriangular(num): if (num < 0): return False # Considering the equation n*(n+1)/2 = num # The equation is : a(n^2) + bn + c = 0 c = (-2 * num) b, a = 1, 1 d = (b * b) - (4 * a * c) if (d < 0): return False # Find roots of equation root1 = ( -b + math.sqrt(d)) / (2 * a) root2 = ( -b - math.sqrt(d)) / (2 * a) # checking if root1 is natural if (root1 > 0 and math.floor(root1) == root1): return True # checking if root2 is natural if (root2 > 0 and math.floor(root2) == root2): return True return False # Driver code n = 55 if (isTriangular(n)): print("The number is a triangular number") else: print("The number is NOT a triangular number") # This code is contributed by Smitha Dinesh Semwal
C#
// C# program to check if a number is a triangular // number using quadratic equation. using System; class GFG { // Returns true if num is triangular static bool isTriangular(int num) { if (num < 0) return false; // Considering the equation n*(n+1)/2 = num // The equation is : a(n^2) + bn + c = 0"; int c = (-2 * num); int b = 1, a = 1; int d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation float root1 = ( -b + (float)Math.Sqrt(d)) / (2 * a); float root2 = ( -b - (float)Math.Sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.Floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.Floor(root2) == root2) return true; return false; } // Driver code public static void Main () { int num = 55; if (isTriangular(num)) Console.WriteLine("The number is a " + "triangular number"); else Console.WriteLine ("The number is NOT " + "a triangular number"); } } //This code is contributed by vt_m.
PHP
<?php // PHP program to check if a number is a // triangular number using quadratic equation. // Returns true if num is triangular function isTriangular($num) { if ($num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0"; $c = (-2 * $num); $b = 1; $a = 1; $d = ($b * $b) - (4 * $a * $c); if ($d < 0) return false; // Find roots of equation $root1 = (-$b + (float)sqrt($d)) / (2 * $a); $root2 = (-$b - (float)sqrt($d)) / (2 * $a); // checking if root1 is natural if ($root1 > 0 && floor($root1) == $root1) return true; // checking if root2 is natural if ($root2 > 0 && floor($root2) == $root2) return true; return false; } // Driver code $num = 55; if (isTriangular($num)) echo("The number is" . " a triangular number"); else echo ("The number " . "is NOT a triangular number"); // This code is contributed // by Code_Mech. ?>
Javascript
<script> // javascript program to check if a number is a // triangular number using quadratic equation. // Returns true if num is triangular function isTriangular(num) { if (num < 0) return false; // Considering the equation // n*(n+1)/2 = num // The equation is : // a(n^2) + bn + c = 0"; var c = (-2 * num); var b = 1, a = 1; var d = (b * b) - (4 * a * c); if (d < 0) return false; // Find roots of equation var root1 = (-b + Math.sqrt(d)) / (2 * a); var root2 = (-b - Math.sqrt(d)) / (2 * a); // checking if root1 is natural if (root1 > 0 && Math.floor(root1) == root1) return true; // checking if root2 is natural if (root2 > 0 && Math.floor(root2) == root2) return true; return false; } // Driver code var num = 55; if (isTriangular(num)) document.write("The number is" + " a triangular number"); else document.write("The number " + "is NOT a triangular number"); // This code is contributed by Rajput-Ji </script>
Producción:
The number is a triangular number
Complejidad de tiempo: O (logn)
Espacio auxiliar: O(1)
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA