http://www.perlmonks.org?node_id=267948

kiat has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I ran some C++ code and it took roughly 15 seconds to compute and print out the solution. I then converted the C++ code to perl and it took perl more than 15 mins to perform the same computation.

I'm wondering if there is something wrong with my perl code? Or is it the case the perl is inherently slow in this sort of computation? I've pasted both pieces of code here for your referral.
//begin c++ code #include<iostream> using namespace std; int main() { unsigned int ans=0; for(unsigned int num=0;num<16777216;++num) { int total=0; unsigned int shift=1; for(int i=1;i<=24;++i) { if(num & shift) { total+=i; } else { total-=i; } shift<<=1; } if(total==0) ++ans; } cout<<"Complete!"<<endl; cout<<"Answer is "<<ans<<endl; } //end c++ code #begin perl code $ans = 0; for($num=0;$num<16777216;$num++){ $total=0; $shift=1; for($i=1;$i<=24;$i++) { if($num & $shift) { $total+=$i; } else { $total-=$i; } $shift <<= 1; } $ans++ if $total == 0; } print "$ans\n"; # end perl code
Can someone enlighten me on the great disparity in speed?