Factorial.java


Dedicated to someone who made me feel like I’m a bad guy.. >.<

The main idea of using recursive method to calculate the factorial is call back the method till n=1. The method has the fuction to calculate n*(n-1). LOL, I’m so sorry if you cant sleep tonight because of this code.🙂

import java.util.*;

/**
 * Factorial.java
 *   A recursive program to calculate the factorial
 *   of a number.
 *   n! = n * (n-1) * (n-2) * ... * 1
 *
 *   A recursive definition of factorial is:
 *   n! = 1          if n <= 1
 *      = n * (n-1)! if n > 2
 *
 * @author Sofa Zainuddin
 * @author Computer Science, Brawijaya University
 * @version 1/15/2011
 */
public class Factorial {
    public static void main (String[] args) {

        Scanner in= new Scanner(System.in);
	int theNum, theFact;

	System.out.println("This program computes the"+
        "factorial of a number.");
	System.out.print("Enter a number: ");
	theNum=in.nextInt();

	theFact = fact(theNum);

	System.out.println(theNum + "! = " + theFact + ".");
    }

    /**
     * Calculate the factorial of n.
     *
     * @param n the number to calculate the factorial of.
     * @return n! - the factorial of n.
     */
    static int fact(int n) {

	// Base Case:
	//    If n <= 1 then n! = 1.
	if (n <= 1) {
	    return 1;
	}
	// Recursive Case:
	//    If n > 1 then n! = n * (n-1)!
	else {
	    return n * fact(n-1);
	}
    }
}
  1. “Dedicated to someone who made me feel like I’m a bad guy.. >.< "

    PREEEEEEETTT

    lalalalalaaaaaa

      • sova.aee
      • January 17th, 2011

      hahaha onyiiiiit…. :p
      jeleg kao nyit.

      • sova.aee
      • January 17th, 2011

      import java.util.Scanner;
      public class onyit {
      public static int perhitungan(int bil){
      int hasil=0;
      //for(int i=1; i< bil; i++)//{
      if (bil<=1){return 1;} else
      hasil = bil* perhitungan(bil-1);//}
      return hasil;
      }
      public static void main(String[] args) {
      Scanner Input = new Scanner(System.in);
      System.out.println("masukkan bilangan yg akan dicari faktorialnya ");
      int bilangan = Input.nextInt();
      System.out.println("hasilnya " + perhitungan(bilangan));
      }
      }

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: