Valor máximo de un número entero para el cual se puede calcular el factorial en una máquina

Programa para encontrar el valor máximo de un número entero para el cual se puede calcular el factorial en una máquina, asumiendo que el factorial se almacena utilizando tipos de datos básicos como long long int.

La idea se basa en que, en la mayoría de las máquinas, cuando cruzamos el límite de un número entero, los valores se vuelven negativos. 

C++

// C++ program to find maximum value of
// an integer for which factorial can
// be calculated on your system
#include <bits/stdc++.h>
using namespace std;
 
int findMaxValue()
{
    int res = 2;
    long long int fact = 2;
    while (1)
    {
        // when fact crosses its size,
        // it gives negative value
        if (fact < 0)
            break;
        res++;
         
        // You cannot use fact = fact*res,
        // for overflow negative condition in C++
        // If you use this then it will give
        // an error,
        // "signed integer overflow: 2432902008176640000 * 21
        // cannot be represented in type 'long long' "
        // To avoid this, use the below code.
        // This error won't occur in languages like java, python,
        // JavaScript. as they have garbage collectors for such errors.
        if(fact > LLONG_MAX/res){
            break;
        }
        else{
            fact = fact*res;
        }
    }
    return res - 1;
}
 
// Driver Code
int main()
{
    cout << "Maximum value of integer : ";
    cout <<  findMaxValue() << endl;
    return 0;
}
 
// The code is contributed by Gautam goel (gautamgoel962)

C

// C program to find maximum value of
// an integer for which factorial can
// be calculated on your system
#include <stdio.h>
 
int findMaxValue()
{
    int res = 2;
    long long int fact = 2;
    while (1)
    {
        // when fact crosses its size,
        // it gives negative value
        if (fact < 0)
            break;
        res++;
        // You cannot use fact = fact*res,
        // for overflow negative condition in C
        // If you use this then it will give
        // an error,
        // "signed integer overflow: 2432902008176640000 * 21
        // cannot be represented in type 'long long' "
        // To avoid this, use the below code.
        // This error won't occur in languages like java, python,
        // JavaScript. as they have garbage collectors for such errors.
        if(fact > LLONG_MAX/res){
            break;
        }
        else{
            fact = fact*res;
        }
    }
    return res - 1;
}
 
// Driver Code
int main()
{
    printf ("Maximum value of integer : %d\n", findMaxValue());
    return 0;
}
 
// The code is contributed by Gautam goel (gautamgoel962)

Java

// Java program to find maximum value of
// an integer for which factorial can be
// calculated on your system
import java.io.*;
import java.util.*;
 
class GFG
{
    public static int findMaxValue()
    {
        int res = 2;
        long fact = 2;
        while (true)
        {
            // when fact crosses its size,
            // it gives negative value
            if (fact < 0)
                break;
            res++;
            fact = fact * res;
        }
        return res - 1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        System.out.println("Maximum value of"+
                                 " integer " +
                              findMaxValue());
    }
}

Python3

# Python3 program to find maximum value of
# an integer for which factorial can be
# calculated on your system
import sys
def findMaxValue():
 
    res = 2;
    fact = 2;
    while (True):
         
        # when fact crosses its size
        # it gives negative value
        if (fact < 0 or fact > sys.maxsize):
            break;
        res += 1;
        fact = fact * res;
    return res - 1;
 
# Driver Code
if __name__ == '__main__':
     
    print("Maximum value of integer:",
                      findMaxValue());
     
# This code is contributed by 29AjayKumar

C#

// C# program to find maximum value of
// an integer for which factorial can
// be calculated on your system
using System;
 
class GFG
{
    public static int findMaxValue()
    {
        int res = 2;
        long fact = 2;
        while (true)
        {
            // when fact crosses its size,
            // it gives negative value
            if (fact < 0)
                break;
            res++;
            fact = fact * res;
        }
        return res - 1;
    }
 
    // Driver Code
    public static void Main()
    {
        Console.Write("Maximum value of"+
                            " integer " +
                         findMaxValue());
    }
}
 
// This code is contributed by nitin mittal

PHP

<?php
// PHP program to find maximum
// value of an integer for which
// factorial can be calculated
// on your system
function findMaxValue()
{
    $res = 2;
    $fact = 2;
    $pos = -1;
    while (true)
    {
        // when fact crosses its size,
        // it gives negative value
        $mystring = $fact;
        $pos = strpos($mystring, 'E');
     
        if ($pos > 0)
            break;
        $res++;
        $fact = $fact * $res;
    }
    return $res - 1;
}
 
// Driver Code
echo "Maximum value of".
           " integer " .
         findMaxValue();
     
// This code is contributed by Sam007
?>

Javascript

<script>
 
// Javascript program to find maximum
// value of an integer for which factorial
// can be calculated on your system
function findMaxValue()
{
    let res = 2;
    let fact = 2;
     
    while (true)
    {
         
        // When fact crosses its size,
        // it gives negative value
        if (fact < 0 || fact > 9223372036854775807)
            break;
             
        res++;
        fact = fact * res;
    }
    return res - 1;
}
 
// Driver Code
document.write("Maximum value of"+
               " integer " + findMaxValue());
 
// This code is contributed by rag2127
 
</script>

Producción : 

Maximum value of integer : 20

Este artículo es una contribución de Pramod Kumar . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
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

Deja una respuesta

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