Walt Mankowski on 2 Jul 2007 00:02:13 -0000 |
On Sun, Jul 01, 2007 at 06:00:42PM -0400, Urb LeJeune wrote: > This is a bit of topic. My math skills are rusty to say the least. > > I'm looking for the formula to calculate the number of iterations required > to reduce N to 1 when N is divided by 2 (rounded up) each iteration. > > To wit, N = 8 > iteration > Number N > 1 4 > 2 2 > 3 1 One way to do this is to find the logarithm base 2 of N, which you can get by dividing the result of log(N) by log(2): sub log2 { my $n = shift; return log($n) / log(2); } One way to round it up would be to use the ceil function in POSIX.pm: use POSIX; . . . sub num_iterations { my $n = shift; return POSIX::ceil(log2($n)); } Walt Attachment:
signature.asc
|
|