How to Calculate Factorial of a Number in Java

    0
    28
    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    How to Calculate Factorial of a Number in Java
    How to Calculate Factorial of a Number in Java

    How to Calculate Factorial of a Number in Java:

    This post talk about the implementation of factorial programming .Mathematically ,if i need to calculate the factorial value it is something like- n!=n*(n-1)*(n-2)*……*1

    well let me take the value of n from user.
    You can visit https://www.techtravelhub.com/2011/12/how-to-take-user-input-in-java-how-i.html
    here for more details while taking input from user.

    The Function is 

    
    private String getData() {
    String userName = null;
    userName = JOptionPane.showInputDialog(null,"What is your Number?","Enter your Number",JOptionPane.QUESTION_MESSAGE);
    System.out.println("Thanks for the Number, " + userName);
    return userName;
    }
     

    When you get the number we need to calculate the factorial

    The Factorial Function in Simple form

    
    private int fact(int  strval) {
    //strval is the value provided by the user
    int j;
    /I am initializing j=1 and val=1 as my output factorial can not be zero.
    j = 1;
    int val;
    val = 1;
    for (j=1;j<=strval;j++)
    {
    val=val*j;
    }
    return val;
    }
     
    
    //definition of  a static variable
    //I am initializing val=1 as my output factorial can not be zero. 
    static int val=1;
    private int recfact(int j) {
    //here the input no will multiplied by val(which is 1 at starting)
    val=val*j;
    //after multiplication decrease the number by 1(by this way we can get (n-1),(n-2) and so on
    j--; 
    // This is the condition till how many time it should run. for this case it should run till 
    //the time j 's value is 1 or greater than 1
    if(j>=1)
    recfact(j);
    return val ;
    }
     

    The Factorial Function using recursion function

     
    private int recfact_withoutstatic(int j) {
    //Here also initialize j as value to h(h is a local variable)
    int h=j;
    //This out is defined to avoid (rule-1)
    int out=1;
    if(j>=1)
    {
    //this is recursive function which is calling the same function again with (n-1),(n-2),(n-3) and so on
    out=h*recfact_withoutstatic(j-1);
    }
    return out;
    }
     

    The Factorial Function using all functions

    
    import java.io.*;
    import javax.swing.JOptionPane;
    public class factorial {
    static int val=1;
    public static void main (String[] args) {
        //  prompt the user to enter their name
         String UserName;
         factorial f=new factorial();
          int i=Integer.parseInt(f.getData());
         System.out.println(f.fact(Integer.parseInt(f.getData())));
         System.out.println(f.recfact(Integer.parseInt(f.getData())));
         System.out.println(f.recfact_withoutstatic(Integer.parseInt(f.getData())));
       }
    
    private String  getData() {
          String userName = null;
          userName = JOptionPane.showInputDialog(null,
          "What is your Number?",
          "Enter your Number",
           JOptionPane.QUESTION_MESSAGE);
          System.out.println("Thanks for the Number, " + userName);
          return userName;
    }
    private int fact(int  strval) {
            int j;
            j = 1;
            int val;
            val = 1;
            for (j=1;j<=strval;j++)
            {
           val=val*j;
            }
              return val;
    }
    private int recfact(int j) {
        val=val*j;
         j--;     
        if(j>=1)
        recfact(j);
        return val ;
    } 
    
        private int recfact_withoutstatic(int j) {
          int h=j;
         int out=1;
         if(j>=1)
         {
          out=h*recfact_withoutstatic(j-1);
         }
          return out;
        } 
    }  // end of factorial class
    
    
    

    The Factorial Rule validations:

    Rule-1 talks about factorial of 0 and its value will be 1

    So let us update the function

    
        private int recfact_withoutstatic(int j) {
            int h=j;
            int out=1;
               if (j==0) {
                return out;   
                            }
           else
          {
               if(j>=1)
                {
                out=h*recfact_withoutstatic(j-1);
                }
          return out;
           } 
        }
    
     

    User needs to give integer value only.

    we will try to implement this on top our function.How??

    
     try{
     System.out.println(f.recfact_withoutstatic(Integer.parseInt(f.getData())));
         }
     catch(Exception e)
       {
        System.out.println("wrong input");
       }
     

    This will exclude the string and non integer values

    So the final code for factorial goes as ::

    
    package component;
    import java.io.*;
    
    import javax.swing.JOptionPane;
    
    public class factorial {
    static int val=1;
       public static void main (String[] args) {
    
          //  prompt the user to enter their name
          String UserName;
           factorial f=new factorial();
      
           try{
         System.out.println(f.fact(Integer.parseInt(f.getData())));
           }
           catch(Exception e) {
               System.out.println("wrong input");
           }
         try
         {
         System.out.println(f.recfact(Integer.parseInt(f.getData())));
         }
           catch(Exception e) {
               System.out.println("wrong input");
           }
           try{
         System.out.println(f.recfact_withoutstatic(Integer.parseInt(f.getData())));
           }
           catch(Exception e) {
               System.out.println("wrong input");
           }
       }
    
    private String  getData() {
        String userName = null;
        userName = JOptionPane.showInputDialog(null,
          "What is your Number?",
          "Enter your Number",
          JOptionPane.QUESTION_MESSAGE);
        System.out.println("Thanks for the Number, " + userName);
        return userName;
    }
    private int fact(int  strval) {
        int j;
        j = 1;
        int val;
        val = 1;
        if (strval==0) {
                    return val; 
                      }
    else
        {     
            for (j=1;j<=strval;j++)
            {
           val=val*j;
            }
              return val;
    }
    }
    private int recfact(int j) {
        if (j==0) {
                    return val; 
                                }
        else
        {
      val=val*j;
         j--;   
        if(j>=1)
        recfact(j);
        return val ;
        }
    }
    
        private int recfact_withoutstatic(int j) {
            int h=j;
            int out=1;
      
         if (j==0) {
             return out; 
         }
         else
         {
    
         if(j>=1)
         {
          out=h*recfact_withoutstatic(j-1);
         }
          return out;
        }
        }
    }  // end of ReadString class
    
     
    Don't miss out!
    Subscribe To Newsletter

    Receive top technical news, lesson ideas, travel tips and more!

    Invalid email address
    Give it a try. You can unsubscribe at any time.

    Spread the love
    • 1
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
      1
      Share

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here