Saturday, 11 August 2018

Java program to discover factorial



Java program to discover factorial of a number: entered number is checked first on the off chance that it is negative, at that point a blunder message is printed. You can likewise discover factorial utilizing recursion, in the code the variable actuality is a whole number so just factorial of little numbers will be effectively shown, which fits in 4 bytes. For vast numbers you can utilize long information compose.

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);
      }
   }
}

Java program for computing factorial of vast numbers

Above program does not give remedy come about for ascertaining factorial of say 20. Since 20! is a vast number and can't be put away in whole number information write which is of 4 bytes. To compute factorial of say hundred we utilize 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);
  }
}

0 comments:

Post a Comment