adsense


Showing posts with label JAVA PROGRAM TO FIND FACTORIAL. Show all posts
Showing posts with label JAVA PROGRAM TO FIND FACTORIAL. Show all posts

Monday, 16 November 2015

JAVA PROGRAM TO FIND FACTORIAL PAGE PAGE 20








COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA PROGRAM TO FIND FACTORIAL










Java program to find factorial


This java program finds factorial of a number. Entered number is checked 
first if its negative then an error message is printed.
Java programming code
import java.util.Scanner;
 
class Factorial
{
   public static void main(String args[])
   {
      int n, c, fact = 1;
 
      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);
 
      n = in.nextInt();
 
      if ( n < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= n ; c++ )
            fact = fact*c;
 
         System.out.println("Factorial of "+n+" is = "+fact);
      }
   }
}
Download Factorial program class file.

Output of program:
 
You can also find factorial using recursion, in the code fact is an integer 
variable so only factorial of small numbers will be correctly displayed or 
which fits in 4 bytes. For large numbers you can use long data type.
Java program for calculating factorial of large numbers
Above program does not give correct result for calculating factorial of say 20. 
Because 20! is a large number and cant be stored in integer data type which is 
of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.

import java.util.Scanner;

import java.math.BigInteger;
 
class BigFactorial
{
  public static void main(String args[])
  {
    int n, c;
    BigInteger inc = new BigInteger("1");
    BigInteger fact = new BigInteger("1");
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input an integer");
    n = input.nextInt();
 
    for (c = 1; c <= n; c++) {
      fact = fact.multiply(inc);
      inc = inc.add(BigInteger.ONE);
    }
 
    System.out.println(n + "! = " + fact);
  }
}
Download Big Factorial class file.

We run the above java program to calculate 100 factorial and following output is obtained.
Input an integer
100
100! = 933262154439441526816992388562667004907
15968264381621468592963895217599993229915608941
46397615651828625369792082722375825118521091686
4000000000000000000000000