Maximum value of an integer for which factorial can be calculated on a machine
Last Updated :
01 Feb, 2023
Program to find maximum value of an integer for which factorial can be calculated on a machine, assuming that factorial is stored using basic data type like long long int.
The idea is based on that fact that, in most of the machines, when we cross limit of integer, the values becomes negative.
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxValue()
{
int res = 2;
long long int fact = 2;
while (1)
{
if (fact < 0)
break ;
res++;
if (fact > LLONG_MAX/res){
break ;
}
else {
fact = fact*res;
}
}
return res - 1;
}
int main()
{
cout << "Maximum value of integer : " ;
cout << findMaxValue() << endl;
return 0;
}
|
C
#include <stdio.h>
int findMaxValue()
{
int res = 2;
long long int fact = 2;
while (1)
{
if (fact < 0)
break ;
res++;
if (fact > LLONG_MAX/res){
break ;
}
else {
fact = fact*res;
}
}
return res - 1;
}
int main()
{
printf ( "Maximum value of integer : %d\n" , findMaxValue());
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int findMaxValue()
{
int res = 2 ;
long fact = 2 ;
while ( true )
{
if (fact < 0 )
break ;
res++;
fact = fact * res;
}
return res - 1 ;
}
public static void main(String[] args)
{
System.out.println( "Maximum value of" +
" integer " +
findMaxValue());
}
}
|
Python3
import sys
def findMaxValue():
res = 2 ;
fact = 2 ;
while ( True ):
if (fact < 0 or fact > sys.maxsize):
break ;
res + = 1 ;
fact = fact * res;
return res - 1 ;
if __name__ = = '__main__' :
print ( "Maximum value of integer:" ,
findMaxValue());
|
C#
using System;
class GFG
{
public static int findMaxValue()
{
int res = 2;
long fact = 2;
while ( true )
{
if (fact < 0)
break ;
res++;
fact = fact * res;
}
return res - 1;
}
public static void Main()
{
Console.Write( "Maximum value of" +
" integer " +
findMaxValue());
}
}
|
PHP
<?php
function findMaxValue()
{
$res = 2;
$fact = 2;
$pos = -1;
while (true)
{
$mystring = $fact ;
$pos = strpos ( $mystring , 'E' );
if ( $pos > 0)
break ;
$res ++;
$fact = $fact * $res ;
}
return $res - 1;
}
echo "Maximum value of" .
" integer " .
findMaxValue();
?>
|
Javascript
<script>
function findMaxValue()
{
let res = 2;
let fact = 2;
while ( true )
{
if (fact < 0 || fact > 9223372036854775807)
break ;
res++;
fact = fact * res;
}
return res - 1;
}
document.write( "Maximum value of" +
" integer " + findMaxValue());
</script>
|
Output :
Maximum value of integer : 20
Time Complexity: The time complexity of this algorithm is O(n). We traverse through the loop and calculate the factorial of the numbers one by one.
Space Complexity: The space complexity of this algorithm is O(1). We are not using any extra space.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...