PROLOG program to calculate factorial

1/5 - (1 vote)

Certainly! Here’s a Prolog program to calculate the factorial of a given number:

factorial(0, 1).
factorial(N, Result) :-
    N > 0,
    N1 is N - 1,
    factorial(N1, SubResult),
    Result is N * SubResult.

Explanation:

  • The first clause of the factorial predicate states that the factorial of 0 is 1.
  • The second clause of the factorial predicate recursively calculates the factorial of a number N. It checks if N is greater than 0, subtracts 1 from N to get N1, recursively calculates the factorial of N1, and multiplies it with N to get the final result.

You can use the program by querying the factorial predicate with a number. For example, to calculate the factorial of 5, you can execute the query:

factorial(5, Result).

The program will unify Result with the factorial value, which in this case will be 120.

14 Trackbacks / Pingbacks

  1. แทงบอล ง่ายๆ กับความแตกต่างระหว่างการแทงบอลแบบเต็งและแบบสเต็ป
  2. skool games alex hormozi
  3. จุดเด่น ของค่ายเกม sexy gaming
  4. thailand tattoo
  5. รับสร้างบ้านหาดใหญ่
  6. hotgraph
  7. ซื้อทราย หาดใหญ่
  8. 온라인카지노사이트
  9. land slot88
  10. poker
  11. MLM programs
  12. สล็อตฝากถอน true walltet ไม่มีบัญชีธนาคาร
  13. gambia senegal
  14. Digital Asset Ownership

Comments are closed.