Thursday, April 4

Factorial number calculation using java with Recursion method and Non-Recursion method

Hi All,


I tried Factorial number calculation using java with Recursion method and non-Recursion method :-)

import java.io.*;

public class factorial {

 public static void main(String[] args) throws IOException {
        // Using Non Recursion method
 
            BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the number");
            int a = Integer.parseInt(object.readLine());
            int fact = 1;
            System.out.println("Using Non Recursion method");
            System.out.println("Factorial of " + a + ":");
            for (int i = 1; i <= a; i++) {
                System.out.print(i + "*");
                fact = fact * i;
            }
            System.out.println(" = "+fact);
   
         // Using Recursion method
      
        int num = new factorial().RecursionFactorial(a);
        System.out.println("Using Recursion method " +num);
    }

    public int RecursionFactorial(int num) {

        int returnValue;

        if (num == 1) {
            return 1;
        }

        returnValue = RecursionFactorial(num - 1) * num;

        return returnValue;

    }
}


output:

Enter the number
8
Using Non Recursion method
Factorial of 8:
1*2*3*4*5*6*7*8* = 40320
Using Recursion method 40320

 

 

 



No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...