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

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

Groovy Factorial Calculation

Groovy

Goal -- WPM

Ready
Exercise Algorithm Area
1class FactorialCalculator {
2
3/**
4* Calculates the factorial of a non-negative integer using an iterative approach.
5* The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
6* For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
7* The factorial of 0 is defined as 1 (0! = 1).
8*
9* @param n The non-negative integer for which to calculate the factorial.
10* @return The factorial of n.
11* @throws IllegalArgumentException if n is negative.
12*/
13public static long calculateFactorial(int n) {
14// Edge case: Factorial is not defined for negative numbers.
15if (n < 0) {
16throw new IllegalArgumentException("Factorial is not defined for negative numbers.");
17}
18
19// Base case: Factorial of 0 is 1.
20if (n == 0) {
21return 1L;
22}
23
24// Initialize the result to 1. Using 'long' to accommodate larger factorial values.
25long result = 1L;
26
27// Iterate from 1 up to n (inclusive) to calculate the product.
28// The loop starts from 1 because multiplying by 0 would always result in 0.
29// The loop condition 'i <= n' ensures that 'n' itself is included in the product.
30for (int i = 1; i <= n; i++) {
31// Multiply the current result by the loop counter.
32// This accumulates the product: 1 * 1, then (1*1) * 2, then (1*1*2) * 3, and so on.
33result *= i;
34}
35
36// Return the computed factorial.
37return result;
38}
39
40/**
41* A simple helper method, though not strictly necessary for this iterative factorial.
42* Demonstrates a helper function concept.
43*
44* @param value A placeholder value.
45* @return The value itself.
46*/
47private static int identityHelper(int value) {
48return value;
49}
50
51public static void main(String[] args) {
52println "Factorial of 0: ${calculateFactorial(0)}" // Expected: 1
53println "Factorial of 1: ${calculateFactorial(1)}" // Expected: 1
54println "Factorial of 5: ${calculateFactorial(5)}" // Expected: 120
55println "Factorial of 10: ${calculateFactorial(10)}" // Expected: 3628800
56println "Factorial of 20: ${calculateFactorial(20)}" // Expected: 2432902008176640000
57
58try {
59println "Factorial of -5: ${calculateFactorial(-5)}" // Expected: Exception
60} catch (IllegalArgumentException e) {
61println "Caught expected exception: ${e.getMessage()}"
62}
63}
64}
Algorithm description viewbox

Groovy Factorial Calculation

Algorithm description:

This Groovy code calculates the factorial of a non-negative integer using an iterative method. The factorial of a number 'n' is the product of all positive integers less than 'n'. For instance, 5! equals 5 * 4 * 3 * 2 * 1, which is 120. The function correctly handles the base case where 0! is defined as 1 and throws an exception for negative inputs. Factorials are fundamental in combinatorics and probability calculations.

Algorithm explanation:

The `calculateFactorial` function computes n! iteratively. It first validates that the input `n` is non-negative; if `n` is less than 0, it throws an `IllegalArgumentException`. The base case is handled: if `n` is 0, it returns 1. For `n > 0`, a `long` variable `result` is initialized to 1. A `for` loop iterates from `i = 1` up to `n`. In each iteration, `result` is multiplied by `i`. This process accumulates the product of all integers from 1 to `n`. The use of `long` helps prevent overflow for moderately large factorials, though extremely large values would still exceed its capacity. The time complexity is O(N) because the loop runs `n` times. The space complexity is O(1) as it only uses a few variables regardless of the input size.

Pseudocode:

function calculateFactorial(n):
  if n is less than 0:
    throw an error "Factorial not defined for negative numbers"

  if n is equal to 0:
    return 1

  result = 1
  for i from 1 to n:
    result = result * i

  return result