Programa para comprobar si N es un número pentagonal – Part 1

Dado un número (N), comprueba si es pentagonal o no. 
Ejemplos: 
 

Input: 12 
Output: Yes
Explanation: 12 is the third pentagonal number

Input: 19
Output: No
Explanation: The third pentagonal number is 12
while the fourth pentagonal number is 22.
Hence 19 is not a pentagonal number.

Los números pentagonales son números que se pueden organizar para formar un pentágono. Si N es un número pentagonal, entonces podemos usar N puntos o puntos para generar un pentágono regular (consulte la figura a continuación).
Los primeros números pentagonales son 1, 5, 12, 22, 35, 51, 70, … 
 

Fuente de la imagen: Wiki
Método I (iterativo) 
Comenzamos observando que el enésimo número pentagonal viene dado por 
P_n = \frac{3*n^2-n}{2}
Siga un proceso iterativo. Sustituya consecutivamente n = 1, 2, 3… en la fórmula y almacene el resultado en alguna variable M. Pare, si M >= N. Después de la iteración, si M es igual a N, entonces N debe ser un número pentagonal. De lo contrario, si M excede a N, entonces N no puede ser un número pentagonal.
Algoritmo 
 

function isPentagonal(N) 
    Set i = 1
    do 
        M = (3*i*i - i)/2
        i += 1
    while M < N
    
    if M == N
        print Yes
    else
        print No

A continuación se muestra la implementación del algoritmo.
 

C++

// C++ program to check
// pentagonal numbers.
#include <iostream>
using namespace std;
 
// Function to determine
// if N is pentagonal or not.
bool isPentagonal(int N)
{
    int i = 1, M;
     
    do {
 
        // Substitute values of i
        // in the formula.
        M = (3*i*i - i)/2;
        i += 1;
    }
    while ( M < N );
     
    return (M == N);
}
 
// Driver Code
int main()
{
    int N = 12;
     
    if (isPentagonal(N))
        cout << N << " is pentagonal " << endl;   
    else
        cout << N << " is not pentagonal" << endl;
     
    return 0;
}

Java

// Java program to check
// pentagonal numbers.
import java.io.*;
 
class GFG {
     
// Function to determine
// if N is pentagonal or not.
static Boolean isPentagonal(int N)
{
    int i = 1, M;
      
    do {
  
        // Substitute values of
        // i in the formula.
        M = (3*i*i - i)/2;
        i += 1;
    }
    while ( M < N );
      
    return (M == N);
}
    public static void main (String[] args) {
    int N = 12;
      
    if (isPentagonal(N))
        System.out.println( N + " is pentagonal " );   
    else
        System.out.println( N + " is not pentagonal");
 
    }
}
 
// This code is contributed by Gitanjali.

Python3

# python3 program to check
# pentagonal numbers.
import math
 
# Function to determine if
# N is pentagonal or not.
def isPentagonal( N ) :
 
    i = 1
    while True:
 
        # Substitute values of i
        # in the formula.
        M = (3 * i * i - i) / 2
        i += 1
     
        if ( M >= N ):
            break
     
    return (M == N)
     
# Driver method
N = 12
if (isPentagonal(N)):
    print(N , end = ' ')
    print ("is pentagonal " )
else:
    print (N , end = ' ')
    print ("is not pentagonal")
 
# This code is contributed by Gitanjali.

C#

// C# program to check pentagonal numbers.
using System;
 
class GFG {
     
// Function to determine
// if N is pentagonal or not.
static bool isPentagonal(int N)
{
    int i = 1, M;
     
    do {
 
        // Substitute values of
        // i in the formula.
        M = (3 * i * i - i) / 2;
        i += 1;
    }
    while ( M < N );
     
    return (M == N);
}
 
// Driver Code
public static void Main ()
{
    int N = 12;
     
    if (isPentagonal(N))
    Console.Write( N + " is pentagonal " );
    else
    Console.Write( N + " is not pentagonal");
 
}
}
 
// This code is contributed by vt_m.

PHP

<?php
// PHP program to check
// pentagonal numbers.
 
// Function to determine
// if N is pentagonal or not.
function isPentagonal(int $N)
{
    $i = 1;
    $M;
     
    do {
 
        // Substitute values of i
        // in the formula.
        $M = (3 * $i * $i - $i) / 2;
        $i += 1;
    }
    while ($M < $N);
     
    return ($M == $N);
}
 
    // Driver Code
    $N = 12;
     
    if (isPentagonal($N))
        echo $N , " is pentagonal " ;
    else
        echo $N ," is not pentagonal" ;
     
// This code is contributed by anuj_67.
?>

Javascript

<script>
// javascript program to check
// pentagonal numbers.
    
// Function to determine
// if N is pentagonal or not.
function isPentagonal(N)
{
    var i = 1, M; 
    do
    {
  
        // Substitute values of
        // i in the formula.
        M = (3 * i * i - i)/2;
        i += 1;
    }
    while ( M < N );
        return (M == N);
}
 
var N = 12;
 
if (isPentagonal(N))
    document.write( N + " is pentagonal " );   
else
    document.write( N + " is not pentagonal");
 
// This code is contributed by Amit Katiyar
</script>

Producción: 
 

12 is pentagonal 

La complejidad de tiempo de este método es O(n) ya que necesitamos calcular valores sucesivos de números pentagonales hasta N.
  
Método 2 (Eficiente) 
La fórmula indica que el n-ésimo número pentagonal depende cuadráticamente de n. Por lo tanto, trate de encontrar la raíz integral positiva de la ecuación N = P(n). 
P(n) = enésimo número pentagonal 
N = Número dado
Resolver para n: 
P(n) = N 
o (3*n*n – n)/2 = N 
o 3*n*n – n – 2*N = 0 … (i)
La raíz positiva de la ecuación (i) 
n = (1 + sqrt(24N+1))/6
Después de obtener n, verifique si es un número entero o no. n es un número entero si n – floor(n) es 0.
La implementación del método se muestra a continuación: 
 

C++

// C++ Program to check a
// pentagonal number
#include <bits/stdc++.h>
using namespace std;
 
// Function to determine if
// N is pentagonal or not.
bool isPentagonal(int N)
{   
    // Get positive root of
    // equation P(n) = N.
    float n = (1 + sqrt(24*N + 1))/6;
     
    // Check if n is an integral
    // value of not. To get the
    // floor of n, type cast to int.
    return (n - (int) n) == 0;
}
 
// Driver Code
int main()
{
    int N = 19;   
    if (isPentagonal(N))
        cout << N << " is pentagonal " << endl;   
    else
        cout << N << " is not pentagonal" << endl;   
    return 0;
}

Java

// Java program to check
// pentagonal numbers.
import java.io.*;
 
class GFG {
     
// Function to determine if
// N is pentagonal or not.
static Boolean isPentagonal(int N)
{
        // Get positive root of
    // equation P(n) = N.
    double n = (1 + Math.sqrt(24*N + 1))/6;
     
    // Check if n is an integral
    // value of not. To get the
    // floor of n, type cast to int.
    return (n - (int) n) == 0;
}
    public static void main (String[] args) {
    int N = 19;
      
    if (isPentagonal(N))
        System.out.println( N + " is pentagonal " );   
    else
        System.out.println( N + " is not pentagonal");
 
    }
}
 
// This code is contributed by Gitanjali.

Python3

# Python3 code Program to 
# check a pentagonal number
 
# Import math library
import math as m
 
# Function to determine if
# N is pentagonal or not
def isPentagonal( n ):
     
    # Get positive root of
    # equation P(n) = N.
    n = (1 + m.sqrt(24 * N + 1)) / 6
     
 
    # Check if n is an integral
    # value of not. To get the
    # floor of n, type cast to int
    return( (n - int (n)) == 0)
 
# Driver Code
N = 19
 
if (isPentagonal(N)):
    print ( N, " is pentagonal " )
else:
    print ( N, " is not pentagonal" )
 
# This code is contributed by 'saloni1297'

C#

// C# program to check pentagonal numbers.
using System;
 
class GFG {
 
    // Function to determine if
    // N is pentagonal or not.
    static bool isPentagonal(int N)
    {
        // Get positive root of
        // equation P(n) = N.
        double n = (1 + Math.Sqrt(24 * N + 1)) / 6;
 
        // Check if n is an integral
        // value of not. To get the
        // floor of n, type cast to int.
        return (n - (int)n) == 0;
    }
     
    // Driver Code
    public static void Main()
    {
        int N = 19;
 
        if (isPentagonal(N))
            Console.Write(N + " is pentagonal ");
        else
            Console.Write(N + " is not pentagonal");
    }
}
 
// This code is contributed by vt_m.

PHP

<?php
// PHP Program to check
// a pentagonal number
 
// Function to determine if
// N is pentagonal or not.
function isPentagonal($N)
{
    // Get positive root of
    // equation P(n) = N.
    $n = (1 + sqrt(24 * $N + 1)) / 6;
     
    // Check if n is an integral
    // value of not. To get the
    // floor of n, type cast to int.
    return ($n - (int) $n) == 0;
}
 
// Driver Code
$N = 19;
if (isPentagonal($N))
    echo $N . " is pentagonal ";
else
    echo $N . " is not pentagonal";
 
// This code is contributed by mits.
?>

Javascript

<script>
// javascript program to check
// pentagonal numbers.
    
// Function to determine if
// N is pentagonal or not.
function isPentagonal(N)
{
     // Get positive root of
    // equation P(n) = N.
    var n = (1 + Math.sqrt(24*N + 1))/6;
     
    // Check if n is an integral
    // value of not. To get the
    // floor of n, type cast to int.
    return (n - parseInt( n) == 0);
}
 
var N = 19;
 
if (isPentagonal(N))
    document.write( N + " is pentagonal " );   
else
    document.write( N + " is not pentagonal");
 
// This code is contributed by Amit Katiyar
</script>

Producción : 
 

19 is not pentagonal

Las complejidades de tiempo y espacio de este método son ambas O(1).
Referencias: 
1) Wikipedia – Números pentagonales 
2) Wolfram Alpha – Números pentagonales
 

Publicación traducida automáticamente

Artículo escrito por Sayan Mahapatra y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *