Ada Factorial Calculation with Edge Cases
with Ada.Text_IO; use Ada.Text_IO; procedure Factorial_Calculator is -- Function to calculate the factorial of a non-negative integer function Calculate_Factorial (N : Natural) return Long_Integer is Result : Long_Integer := 1; begin -- Base case: factorial of 0 is 1 if N = 0 the...
This Ada program calculates the factorial of a non-negative integer using an iterative approach. The `Calculate_Factorial` function handles the base cases for 0 and 1, and then iteratively multiplies numbers from 2 up to...
The `Calculate_Factorial` function computes the factorial of a given non-negative integer `N`. It initializes a `Long_Integer` variable `Result` to 1. The function first checks for the base cases: if `N` is 0 or 1, it directly returns 1, as the factorial of both is 1. For `N` greater than 1, it enters a loop that iterates from 2 up to `N`. In each iteration, it multiplies the current `Result` by the loop counter `I`. This process continues until all numbers from 2 to `N` have been multiplied into `Result`. The time complexity is O(N) because the loop runs `N-1` times. The space complexity is O(1) as it uses a fixed amount of extra space for variables regardless of the input size. The use of `Long_Integer` helps mitigate overflow for moderately large inputs, though extremely large inputs could still exceed its capacity.
FUNCTION Calculate_Factorial(N): IF N = 0 OR N = 1 THEN RETURN 1 END IF RESULT = 1 FOR I FROM 2 TO N: RESULT = RESULT * I END FOR RETURN RESULT END FUNCTION