Check if N-factorial is divisible by X^Y
Last Updated :
12 May, 2021
Given three integers N, X and Y, the task is to check that if N! is divisible by XY
Examples:
Input: N = 10, X = 2, Y = 8
Output: YES
Explanation:
Factorial of 10 is – 3628800
and the value of XY = 28 = 256
Since, 3628800 is divisible by 256, therefore answer is YES.
Input: N = 5, X = 2, Y = 4
Output: NO
Explanation:
The Factorial of 5 is – 120
and the value of XY = 24 = 16
Since, 3628800 is not divisible by 16, therefore answer is NO.
Approach: The idea is to find the value of N-factorial and XY separately and then check if the value of N-factorial is divisible XY.
Algorithm:
Note: This approach does not work for large values of N.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void check( int n, int x, int y){
int fact = 1;
for ( int i = 2; i <= n; i++) {
fact *= i;
}
int divisor = pow (x, y);
if (fact % divisor == 0)
cout << "YES" ;
else
cout << "NO" ;
}
int main()
{
int n = 10;
int x = 2;
int y = 8;
check(n, x, y);
}
|
Java
import java.util.*;
import java.lang.*;
class divisible {
public static void check( int n,
int x, int y){
long fact = 1 ;
for ( int i = 2 ; i <= n; i++) {
fact *= i;
}
long divisor = ( long )Math.pow(x, y);
if (fact % divisor == 0 )
System.out.println( "YES" );
else
System.out.println( "NO" );
}
public static void main(String args[])
{
int n = 10 ;
int x = 2 ;
int y = 8 ;
check(n, x, y);
}
}
|
Python3
def check(n, x, y) :
fact = 1 ;
for i in range ( 2 , n + 1 ) :
fact * = i;
divisor = x * * y;
if (fact % divisor = = 0 ) :
print ( "YES" );
else :
print ( "NO" );
if __name__ = = "__main__" :
n = 10 ;
x = 2 ;
y = 8 ;
check(n, x, y);
|
C#
using System;
class divisible {
public static void check( int n,
int x, int y){
long fact = 1;
for ( int i = 2; i <= n; i++) {
fact *= i;
}
long divisor = ( long )Math.Pow(x, y);
if (fact % divisor == 0)
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
public static void Main(String []args)
{
int n = 10;
int x = 2;
int y = 8;
check(n, x, y);
}
}
|
Javascript
<script>
function check(n,x,y)
{
var fact = 1;
for ( var i = 2; i <= n; i++) {
fact *= i;
}
var divisor = Math.pow(x, y);
if (fact % divisor === 0)
document.write( "YES" );
else
document.write( "NO" );
}
var n = 10;
var x = 2;
var y = 8;
check(n, x, y);
</script>
|
PHP
<?php
function check( $n , $x , $y )
{
$fact = 1;
for ( $i = 2; $i <= $n ; $i ++) {
$fact *= $i ;
}
$divisor = pow( $x , $y );
if ( $fact % $divisor === 0)
echo ( "YES" );
else
echo ( "NO" );
}
$n = 10;
$x = 2;
$y = 8;
check( $n , $x , $y );
?>
|
Output:
YES
Performance Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1).
Share your thoughts in the comments
Please Login to comment...