Posts Tagged ‘ java ’

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

Morning Head Error Report!!!


import java.util.*;

public class Lesson1 {
public static void main (String [] args){
System.out.println(“Hello world”);
}
}

06:49 PM, I can’t recognize my self. Yeah, just like “pain in the ass”, all I can remember is “Hello world”, my first Java code. C’mon wake up boy, start to think of it. Ok enough with my squawk.

Last night I get my ambition back, lol I dont know why. I have an ambition to develop a Java program, especially in database. This is my first goal: no error report, runing nicely, friendly GUI for user.

My mood: totally not sure about this project 😦 . J-creator> File> New File> Project_One. Ok, time to start.