in reply to Re^2: Why is this code so much slower than the same algorithm in C?
in thread Why is this code so much slower than the same algorithm in C?

snowhare,
Can this be reduced even further?
for values of x > 20 if x % 12 == 0 then x % 6 == 0
Is there a reason to have them both?

Update: In other words, order the list in descending order removing any exact multiples of previous items. When you reach 16, one of two things will happen. Either there will be a remainder and it will exit the loop or there won't be a remainder and it will continue. There is no need to test 8 after 16.

Cheers - L~R

  • Comment on Re^3: Why is this code so much slower than the same algorithm in C?
  • Download Code

Replies are listed 'Best First'.
Re^4: Why is this code so much slower than the same algorithm in C? (2s)
by tye (Sage) on Dec 10, 2008 at 20:46 UTC
    perl -le "do { $i += 20 } while( $i%3||$i%7||$i%11||$i%13||$i%16||$i%1 +7||$i%19 ); print $i" 77597520
    or just
    perl -le "print 3*5*7*11*13*16*17*19"

    Update: Replace 3 with 9 in both samples above to get the correct answer, as noted and further explained in the replies below.

    - tye        

      You've got an extra factor of 3. The correct answer is 232792560. ;)

        Yes, thanks. The "last until $i%..." logic has so many negations in it (many of them implicit rather than explicit) that it took several iterations to work out some stuff that I had backwards. Limbic~Region and others in the chatterbox helped out and pointed out that keeping 8 while dropping 16 was backward. But my error of keeping 3 while dropping 9 was not caught (and when I went to check my work, I did not see that anybody had reported the output of their lengthy test runs, just the running times, and I had things to do and so made no plans to tie up my computer for minutes in order to get the answer for comparison).

        I'll update the node to note the require s/3/9/. Thanks again.

        - tye        

      Why do that much analysis and then throw away so much speed by not using a lexical? Also why not finish the analysis?
      perl -le 'my $i = 0;do { $i += 20 } while( $i%46558512 ); print $i' 232792560
      Performance is essentially the same if you write 46558512 as (9*7*11*13*16*17*19).

        My first script takes 2 seconds to run so I doubt you can type "my $i = 0;" faster than the running time you'd save. "That much analysis"? I did hardly any. And I believe my second one-liner already trumps either of your contributions. q-:

        - tye        

Re^4: Why is this code so much slower than the same algorithm in C?
by snowhare (Friar) on Dec 11, 2008 at 19:06 UTC
    Good catch.
    #!/usr/bin/perl use integer; my $i = 0; while ($i += 20) { last unless ( $i % 19 or $i % 18 or $i % 17 or $i % 16 or $i % 15 or $i % 14 or $i % 13 or $i % 12 or $i % 11 ); } print "Number: $i\n";
    Is 17% faster than my original version.