First digit in factorial of a number
Last Updated :
27 Jan, 2023
Given a positive integer n, find the first digit in its factorial.
Examples :
Input : n = 5
Output : 1
Factorial of 5 is 120 and first
digit is 1.
Input : 1000
Output : 4
A simple solution is to compute factorial of number, then find first digit in it.
The above solution causes overflow soon. A better solution is to use the fact that factorial contains trailing 0s and removing trailing 0s does not change first digit. For example, first digit of x * y is same as x * y * 100 for x > 0 and y > 0.
C++
#include <bits/stdc++.h>
using namespace std;
int firstDigit( int n)
{
long long int fact = 1;
for ( int i = 2; i <= n; i++) {
fact = fact * i;
while (fact % 10 == 0)
fact = fact / 10;
}
while (fact >= 10)
fact = fact / 10;
return fact;
}
int main()
{
int n = 5;
cout << firstDigit(n);
return 0;
}
|
Java
class GFG{
static int firstDigit( int n)
{
int fact = 1 ;
for ( int i = 2 ; i <= n; i++) {
fact = fact * i;
while (fact % 10 == 0 )
fact = fact / 10 ;
}
while (fact >= 10 )
fact = fact / 10 ;
return fact;
}
public static void main(String[] args)
{
int n = 5 ;
System.out.println(firstDigit(n));
}
}
|
Python3
import math
def firstDigit(n) :
fact = 1
for i in range ( 2 , n + 1 ) :
fact = fact * i
while (fact % 10 = = 0 ) :
fact = int (fact / 10 )
while (fact > = 10 ) :
fact = int (fact / 10 )
return math.floor(fact)
n = 5
print (firstDigit(n))
|
C#
using System;
class GFG {
static int firstDigit( int n)
{
int fact = 1;
for ( int i = 2; i <= n; i++)
{
fact = fact * i;
while (fact % 10 == 0)
fact = fact / 10;
}
while (fact >= 10)
fact = fact / 10;
return fact;
}
public static void Main()
{
int n = 5;
Console.Write(firstDigit(n));
}
}
|
PHP
<?php
function firstDigit( $n )
{
$fact = 1;
for ( $i = 2; $i <= $n ; $i ++)
{
$fact = $fact * $i ;
while ( $fact % 10 == 0)
$fact = $fact / 10;
}
while ( $fact >= 10)
$fact = $fact / 10;
return floor ( $fact );
}
$n = 5;
echo firstDigit( $n );
?>
|
Javascript
<script>
function firstDigit(n)
{
let fact = 1;
for (let i = 2; i <= n; i++)
{
fact = fact * i;
while (fact % 10 == 0)
fact = fact / 10;
}
while (fact >= 10)
fact = fact / 10;
return (Math.round(fact));
}
let n = 5;
document.write(firstDigit(n));
</script>
|
Time Complexity: O(n * log10(n)), where log10(n) time is to remove trailing zeroes and it is running n times
Auxiliary Space: O(1)
The above code also fails for slightly higher values. The best idea seems to be to find factorial of large number and then find first digit.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...