Advertisement
TheSTRIG

Lab7

Nov 7th, 2014
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Test2 {
  4.     public static long method1 (int n) {
  5.         // n! -> n x (n-1) x (n-2) x ... x 1
  6.         // base case adalah saat 1! -> hasilnya 1
  7.         // reccurence case adalah saat tidak 1
  8.         // 2! = 2 x 1
  9.         // 3! = 3 x 2 x 1
  10.         // 4! = 4 x 3 x 2 x 1
  11.         // 2! = 2 x 1!
  12.         // 3! = 3 x 2!
  13.         // 4! = 4 x 3!
  14.        
  15.         if (n <= 1){
  16.             return 1;
  17.         } else {
  18.             return n * method1(n-1);
  19.         }
  20.     }
  21.     public static String method3 (int n) {
  22.         if (n <= 1){
  23.             return "1";
  24.         } else {
  25.             return n + "*" + method3(n-1);
  26.         }
  27.     }
  28.     public static String method2 (int n) { 
  29.         //n! = n x n-1 x n-2 x ... x 1
  30.        
  31.         String a = "";
  32.         System.out.print(n+"! = ");
  33.         for (int i = n; i > 1; i--) {
  34.             System.out.print(i+"*");
  35.         }
  36.         System.out.print("1");
  37.         return a;
  38.        
  39.     }
  40.    
  41.     public static void main (String[] args) {
  42.         Scanner in = new Scanner(System.in);
  43.         System.out.print("Masukan angka: ");
  44.         int angka = in.nextInt();
  45.        
  46.         System.out.println(angka + "! = " + method3(angka) + " = " + method1(angka));
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement