I tried PDL, but it was also very slow (about 49 minutes):
use strict; use PDL::LiteF; use PDL::Primitive; use PDL::Reduce; use PDL::Types; use integer; my ($ans, $total, $total2, $sum, $num, $ones, $zeros); my $shifts = long ( 0, 1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7, 1 << 8, 1 << 9, 1 << 10, 1 << 11, 1 << 12, 1 << 13, 1 << 14, 1 << 15, 1 << 16, 1 << 17, 1 << 18, 1 << 19, 1 << 20, 1 << 21, 1 << 22, 1 << 23 ); $ans = 0; for my $num (0 .. 16777216) { $sum = sum(which($shifts & $num)); $total = 2*$sum - 300; $ans++ if $total == 0; } print "$ans\n";
I did much better with Inline::C (about 4 seconds after the first time):
use Inline C; print "answer is ", bitlevels(), "\n"; __END__ __C__ /* begin c++ code */ /* #include<iostream> */ /* using namespace std; */ int bitlevels() { unsigned int ans=0; int num, total, i; unsigned int shift; 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; } if(total==0) ++ans; } return ans; } /* end c++ code */

In reply to Re: Believably slow.. by tall_man
in thread Unbelievably slow.. by kiat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.