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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|