in reply to Simple arithmetic?

Inspired by previous answers. As usual, the absence of bugs is totally not guaranteed :) But should be something like that...
use strict; use warnings; # greatest common multiple sub gcm { my ( $max, $num ) = @_; for ( my $c = 1; ( $num & 1 ) == 0 && $c < 4096; $c <<= 1 ) { $num >>= 1; } my $lcm = 4096 * $num; # least common multiple return int( $max / $lcm ) * $lcm; } sub pretty { return shift =~ s/\d \K (?= (?: \d{3} )+ \z)/_/xgr; } print pretty( gcm( 2_147_483_648, 12 ) ), "\n"; print pretty( gcm( 3_221_225_472, 5007 ) ), "\n"; print pretty( gcm( 4_096, 4_096 ) ), "\n"; print pretty( gcm( 8_192, 8_192 ) ), "\n"; print pretty( gcm( 15_000, 8_192 ) ), "\n"; print pretty( gcm( 17_000, 8_192 ) ), "\n"; print pretty( gcm( 17_000, 10 ) ), "\n";
output:
2_147_475_456 3_219_861_504 4_096 8_192 8_192 16_384 0

Replies are listed 'Best First'.
Re^2: Simple arithmetic?
by BrowserUk (Patriarch) on Mar 08, 2015 at 12:27 UTC
    Inspired by previous answers.

    I like your way of incorporating hdb's powers-of-two observation into the GCD() calculation.

    the absence of bugs is totally not guaranteed

    Understood. It's my responsibility to test code I use.

    It stands up to all the likely scenarios (for my application) that I've tested. Thank you.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
    In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

      Of course, my post came later, so the observation is this Anonymus Monk's own original observation. If in addition, as you comment above, R is prime (different from 2) or only odd, then the LCM is always 4096*R, so the whole discussion redundant...

        Of course, my post came later, so the observation is this Anonymus Monk's own original observation.
        No, I did mean 'answers' - both of them (the first one doesn't count, of course :) I'm kind of ungood at math - that's the reason for bitshifts, they're more 'visual' :)