ตัวอย่างชวา - ปัจจัย
factorial ของจำนวนเต็มบวก (อังกฤษ: ปัจจัย) ทั้งหมดน้อยกว่าและเท่ากับผลคูณของจำนวนจำนวนเต็มบวกและมีปัจจัยจาก 0 เป็น 1 เขียนจำนวนธรรมชาติ n ปัจจัย n!
นั่นคือ n! = 1 × 2 × 3 × ... × n แฟกทอซ้ำยังสามารถกำหนด :! 0 = 1, N = (n-1) × n !!
ตัวอย่างต่อไปนี้แสดงให้เห็นถึงการดำเนินงานของรหัสปัจจัยชวา:
/* author by w3cschool.cc MainClass.java */ public class MainClass { public static void main(String args[]) { for (int counter = 0; counter <= 10; counter++){ System.out.printf("%d! = %d\n", counter, factorial(counter)); } } public static long factorial(long number) { if (number <= 1) return 1; else return number * factorial(number - 1); } }
รหัสดังกล่าวจะดำเนินการส่งออกเป็น:
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800