Tejal Patel Tejal Patel - 2 months ago 15
Java Question

Program to input a number and if its a factorial number then output factorial series else false

import java.util.*;
class Factorial{

void factNum(int n){
int fact=1;
ArrayList<Integer> al=new ArrayList<Integer>();
for(int i=1;fact<=n;i++){
for(int j:al){



public static void main(String args[]){

Scanner scan=new Scanner(System.in);
Factorial f=new Factorial();
System.out.println("Enter the Integer");
int num=scan.nextInt();

I wrote this code so that when I input number 24 which is factorial I will get 1 2 3 4 as a output and when I input 23 i should get output as false. My code is almost correct but the problem is that when I enter number which does not belong to factorial series, I am not getting False as output. Please can anyone help me where in this code I can keep System.out.print("False"); Statement.


You can use flag value as shown in below code to keep track of the condition of whether the number is factorial or not.

public static void factNum(int n) {

    int fact = 1;
    ArrayList<Integer> al = new ArrayList<Integer>();

    boolean flag = false;

    for (int i = 1; fact <= n; i++) {
        fact = fact * i;
        if (fact == n) {
            flag = true;
            for (int j : al) {