# factorial(21) and Mac System Ruby

> Last updated: 2012-11-02

I just got a new macbook air and discovered this problem with the system ruby. Here’s a simple implementation of factorial.

```
def fact(n)
  return 1 if n.between?(0, 1)
  (2..n).inject(:*)
end
```

When you run it in irb it does what you’d expect:

```
>> fact(1)
=> 1
>> fact(0)
=> 1
>> fact(2)
=> 2
>> fact(5)
=> 120
>> fact(10)
=> 3628800
>> fact(20)
=> 2432902008176640000
```

Until the result won’t fit in a Fixnum and needs to fit in a big num. Then it overflows.

```
>> fact(21)
=> -4249290049419214848
```

My macbook shipped with this version of ruby.

```
ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin12.0]
```

This bug isn’t in ruby, its in the version that Apple is shipping on the newest macbooks. Using rbenv I installed the same patch version and re-ran the factorials.

```
>>fact(1)
=> 1
>>fact(20)
=> 2432902008176640000
>>fact(21)
=> 51090942171709440000
```

Please enable JavaScript to view the [comments powered by Disqus.](https://disqus.com/?ref_noscript)

 ![Aja Hammerly](/img/traditionalheadshot.jpg)

Aja Hammerly

Seattle, WA

### library\_books Series Index 

- [Developer Relations](/series#developer-relations)4
- [Machine Learning Basics](/series#machine-learning-basics)3
- [Battleship](/series#battleship)5
- [Talks I Love](/series#talks-i-love)6
- [Algorithms with Auntie Aja](/series#algorithms-with-auntie-aja)3
- [Ruby and GCP](/series#ruby-and-gcp)5
- [Playing with Data](/series#playing-with-data)3
- [Kubernetes & Rails](/series#kubernetes-rails)3
- [Learn To Code Resources](/series#learn-to-code-resources)3
- [Testing Anti-Patterns](/series#testing-anti-patterns)5
