Number of trailing zeroes in base 16 representation of N!
Last Updated :
14 Nov, 2022
Given an integer N, the task is to find the number of trailing zeroes in the base 16 representation of the factorial of N.
Examples:
Input: N = 6
Output: 1
6! = 720 (base 10) = 2D0 (base 16)
Input: N = 100
Output: 24
Approach:
- Number of trailing zeroes would be the highest power of 16 in the factorial of N in base 10.
- We know that 16 = 24. So, the highest power of 16 is equal to the highest power 2 in the factorial of N divided by 4.
- To calculate the highest power of 2 in N!, we can use Legendre’s Formula.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
ll getTrailingZeroes(ll n)
{
ll count = 0;
ll val, powerTwo = 2;
do {
val = n / powerTwo;
count += val;
powerTwo *= 2;
} while (val != 0);
return (count / 4);
}
int main()
{
int n = 6;
cout << getTrailingZeroes(n);
}
|
Java
class GfG
{
static long getTrailingZeroes( long n)
{
long count = 0 ;
long val, powerTwo = 2 ;
do
{
val = n / powerTwo;
count += val;
powerTwo *= 2 ;
} while (val != 0 );
return (count / 4 );
}
public static void main(String[] args)
{
int n = 6 ;
System.out.println(getTrailingZeroes(n));
}
}
|
Python3
def getTrailingZeroes(n):
count = 0
val, powerTwo = 1 , 2
while (val ! = 0 ):
val = n / / powerTwo
count + = val
powerTwo * = 2
return (count / / 4 )
n = 6
print (getTrailingZeroes(n))
|
C#
using System;
class GFG
{
static long getTrailingZeroes( long n)
{
long count = 0;
long val, powerTwo = 2;
do
{
val = n / powerTwo;
count += val;
powerTwo *= 2;
} while (val != 0);
return (count / 4);
}
public static void Main()
{
int n = 6;
Console.Write(getTrailingZeroes(n));
}
}
|
PHP
<?php
function getTrailingZeroes( $n )
{
$count = 0;
$val ; $powerTwo = 2;
do
{
$val = (int)( $n / $powerTwo );
$count += $val ;
$powerTwo *= 2;
} while ( $val != 0);
return ( $count / 4);
}
$n = 6;
echo (getTrailingZeroes( $n ));
?>
|
Javascript
<script>
function getTrailingZeroes(n)
{
let count = 0;
let val, powerTwo = 2;
do {
val = Math.floor(n / powerTwo);
count += val;
powerTwo *= 2;
} while (val != 0);
return (Math.floor(count / 4));
}
let n = 6;
document.write(getTrailingZeroes(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...