Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anticipate factorial overflow

Tags:

algorithm

I'm wondering how could I anticipate whether the next iteration will generate an integer overflow while calculating the factorial F or not?

Let's say that at each iteration I have an int I and the maximum value is MAX_INT.

It sounds like a homework, I know. It's not. It's just me asking myself "stupid" questions.

Addendum

I though about, given a number of BITS (the width an integer can take, in bits), I could round up the number I to the next power of two, and detect if a shift to left would exceed BITS. But how would that look like, algorithmically?

like image 409
Flavius Avatar asked Jun 06 '10 21:06

Flavius


1 Answers

Alternative hint:

a * b ≤ MAX_INT 

is equivalent to

a ≤ MAX_INT / b

if b > 0.

like image 80
kennytm Avatar answered Sep 24 '22 02:09

kennytm