ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Calculate Factorial Iteratively

Dart

Goal -- WPM

Ready
Exercise Algorithm Area
1int calculateFactorial(int n) {
2if (n < 0) {
3throw ArgumentError('Factorial is not defined for negative numbers.');
4}
5if (n == 0 || n == 1) {
6return 1;
7}
8
9int result = 1;
10for (int i = 2; i <= n; i++) {
11result *= i;
12}
13return result;
14}
Algorithm description viewbox

Calculate Factorial Iteratively

Algorithm description:

This function computes the factorial of a non-negative integer. The factorial of a number is the product of all positive integers less than or equal to that number. It's a fundamental concept in combinatorics and probability, used in calculating permutations and combinations. For instance, it helps determine the number of ways to arrange a set of items.

Algorithm explanation:

The `calculateFactorial` function computes the factorial of `n` iteratively. It first handles invalid input (negative numbers) by throwing an `ArgumentError`. The base cases for `n = 0` and `n = 1` are handled by returning 1, as 0! and 1! are both defined as 1. For `n > 1`, a loop iterates from 2 up to `n`, multiplying the `result` by the current loop variable `i`. The time complexity is O(n) because the loop runs `n-1` times. The space complexity is O(1) as it uses a constant amount of extra space. Edge cases include negative input and the base cases of 0 and 1.

Pseudocode:

FUNCTION calculateFactorial(integer n):
  IF n < 0 THEN
    THROW error 'Factorial is not defined for negative numbers.'
  END IF
  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