in reply to Re^2: Simple arithmetic? (And the winner is ... )
in thread Simple arithmetic?

And no sooner have I said that, and I think of a way to use _BitScanForward64() that improves upon the original by 70+%:

C:\test\C>gcm anonyM: gcm for s=2147483648 & r=1 to 1073741824 took:8.535316994670 anonyM: gcm2 for s=2147483648 & r=1 to 1073741824 took:2.271266720696

Pre-masking the scanned var, avoids the later subtraction being conditional:

U64 gcm2( U64 max, U64 lcm ) { I32 b; _BitScanForward64( &b, lcm & 0xfff ); lcm <<= ( 12 - b ); return ( max / lcm ) * lcm; }

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

Replies are listed 'Best First'.
Re^4: Simple arithmetic? (And the winner is ... )
by oiskuu (Hermit) on Mar 09, 2015 at 21:52 UTC

    Fixed version with a quick demonstration of the problem:

    #include <stdio.h> #include <stdint.h> #include <stdlib.h> uint64_t gcm2( uint64_t max, uint64_t lcm ) { int b = __builtin_ctzl( lcm & 0xfff ); lcm <<= ( 12 - b ); return ( max / lcm ) * lcm; } uint64_t gcm(uint64_t max, uint64_t lcm) { lcm <<= 12 - __builtin_ctzl(lcm | 0x1000); return max - (max % lcm); } int main(int argc, char *argv[]) { unsigned long max = 12345 << 10; while (argc-- > 1) { unsigned long v = strtoul(argv[argc], NULL, 10); printf("gcm2(%lu,%lu) = %lu\n", max, v, gcm2(max, v)); printf("gcm(%lu,%lu) = %lu\n", max, v, gcm(max, v)); } return 0; }
    $ ./a.out 12 77 4096
    gcm2(12641280,4096) = 0
    gcm(12641280,4096) = 12640256
    gcm2(12641280,77) = 12615680
    gcm(12641280,77) = 12615680
    gcm2(12641280,12) = 12632064
    gcm(12641280,12) = 12632064