in reply to Re^3: 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?

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        

Replies are listed 'Best First'.
Re^5: Why is this code so much slower than the same algorithm in C? (2s)
by snowhare (Friar) on Dec 11, 2008 at 19:11 UTC
    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        

Re^5: Why is this code so much slower than the same algorithm in C? (2s)
by tilly (Archbishop) on Dec 15, 2008 at 13:19 UTC
    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        

        Can you type that in under 0.5 s? If so, then the my is a win. And in the thread you previously discussed having talked about it in chatter and corrected 2 mistakes. I took that as a sing that you did some analysis.

        I don't remember the second one-liner. It is obviously faster, but doesn't fit with the theme of trying to micro-optimize the loop.