factorial function Null safety

int factorial(
  1. int k
)

Factorial function.

Throws ArgumentError if the argument is negative.

Uses double-precision floating-point values in browsers, which means that precision issues may appear when factorial values reach 48 bits.

Examples

import 'package:calc/calc.dart';

void main() {
  factorial(0); // --> 1
  factorial(1); // --> 1
  factorial(2); // --> 2
  factorial(3); // --> 6
  factorial(4); // --> 24
  factorial(5); // --> 120
  factorial(20); // --> 2432902008176640000
}

Implementation

int factorial(int k) {
  // TODO: Faster algorithm
  if (k < 0) {
    throw ArgumentError.value(k);
  }
  if (k == 0) {
    return 1;
  }
  var result = k;
  k--;
  while (k > 1) {
    result *= k;
    k--;
  }
  return result;
}