Check if a given number is factorial of any number
Given a number n, the task is to determine whether n can be a factorial of some number x
Examples:
Input: N = 24
Output: Yes
Explanation: 4! = 24
Input: N = 25
Output: No
Approach:
For a number to be a factorial of any number it must be divisible by all the numbers from 1 to that number. So in this approach
We keep on dividing the number if it is completely divisible till it is no longer divisible.
Then we check the final number of n, if it is 1 we return true else we return false.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool isFactorial( int n)
{
for ( int i = 1;; i++) {
if (n % i == 0) {
n /= i;
}
else {
break ;
}
}
if (n == 1) {
return true ;
}
else {
return false ;
}
}
int main()
{
int n = 24;
bool ans = isFactorial(n);
if (ans == 1) {
cout << "Yes\n" ;
}
else {
cout << "No\n" ;
}
return 0;
}
|
Java
class GFG
{
static boolean isFactorial( int n)
{
for ( int i = 1 ;; i++)
{
if (n % i == 0 )
{
n /= i;
}
else
{
break ;
}
}
if (n == 1 )
{
return true ;
}
else
{
return false ;
}
}
public static void main (String[] args)
{
int n = 24 ;
boolean ans = isFactorial(n);
if (ans == true )
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def isFactorial(n) :
i = 1
while ( True ) :
if (n % i = = 0 ) :
n / / = i
else :
break
i + = 1
if (n = = 1 ) :
return True
else :
return False
if __name__ = = "__main__" :
n = 24
ans = isFactorial(n)
if (ans = = 1 ) :
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static Boolean isFactorial( int n)
{
for ( int i = 1;; i++)
{
if (n % i == 0)
{
n /= i;
}
else
{
break ;
}
}
if (n == 1)
{
return true ;
}
else
{
return false ;
}
}
public static void Main (String[] args)
{
int n = 24;
Boolean ans = isFactorial(n);
if (ans == true )
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function isFactorial(n)
{
for ( var i = 1;; i++)
{
if (n % i == 0)
{
n = parseInt(n/i);
}
else
{
break ;
}
}
if (n == 1)
{
return true ;
}
else
{
return false ;
}
}
var n = 24;
var ans = isFactorial(n);
if (ans == 1)
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
C
#include <stdio.h>
#include<stdbool.h>
bool isFactorial( int n)
{
for ( int i = 1;; i++) {
if (n % i == 0) {
n /= i;
}
else {
break ;
}
}
if (n == 1) {
return true ;
}
else {
return false ;
}
}
int main()
{
int n = 24;
bool ans = isFactorial(n);
if (ans == 1) {
printf ( "Yes\n" );
}
else {
printf ( "No\n" );
}
}
|
Time Complexity: O(log10n)
Auxiliary Space: O(1)
Last Updated :
10 Jul, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...