and 1 contributors

# NAME

Math::NumSeq::Factorials -- factorials i! = 1*2*...*i

# SYNOPSIS

`````` use Math::NumSeq::Factorials;
my \$seq = Math::NumSeq::Factorials->new;
my (\$i, \$value) = \$seq->next;``````

# DESCRIPTION

The factorials being product 1*2*3*...*i, 1 to i inclusive.

``````    starting i=1
1, 2, 6, 24, 120, ...``````

# FUNCTIONS

See "FUNCTIONS" in Math::NumSeq for behaviour common to all sequence classes.

`\$seq = Math::NumSeq::Factorials->new ()`

Create and return a new sequence object.

`\$seq->seek_to_i(\$i)`

Move the current sequence position to `\$i`. The next call to `next()` will return `\$i` and corresponding value.

## Random Access

`\$value = \$seq->ith(\$i)`

Return `1*2*...*\$i`. For `\$i==0` this is considered an empty product and the return is 1.

`\$bool = \$seq->pred(\$value)`

Return true if `\$value` is a factorial, ie. equal to `1*2*...*i` for some i.

`\$i = \$seq->value_to_i_floor(\$value)`

Return the index i of `\$value` or if it's not a factorial then the next below `\$value`.

`\$i = \$seq->value_to_i_estimate(\$value)`

Return an estimate of the i corresponding to `\$value`.

# FORMULAS

## Value to i Estimate

The current code uses Stirling's approximation

``    log(n!) ~= n*log(n) - n``

by seeking an i for which the target factorial "value" has

``    i*log(i) - i == log(value)``

Newton's method is applied to solve for i,

``````    target=log(value)
f(x) = x*log(x) - x - target,     wanting f(x)=0
f'(x) = log(x)

iterate next_x = x - f(x)/f'(x)
= (x+target)/log(x)``````

Just two iterations is quite close

``````    target = log(value)
i0 = target
i1 = (i0+target)/log(target)
= 2t/log(target)
i2 = (i1+target)/log(i1)

i ~= int(i2)``````