All,
I recently watched this
youtube video talking about the sequence 2, 3, 4, 82000. 82000 is the smallest integer that when written in base 2, 3, 4 and 5 is done so only with 1s and 0s. I tried to come up with an easy way to test if a number in base 10 would be written with only 1s and 0s in another base without fully converting the number. I came up with the following (untested as I am without access to Perl at the moment).
Can you come up with a more efficient way working with the constraint that you aren't converting completely between bases?
sub only_1_0_in_base_x {
my ($num, $base) = @_;
if ($num / $base != int($num / $base)) {
$num--;
return 0 if $num / $base != int($num / $base);
}
my $exponent = int(log($num) / log($base));
my $max = 0;
$max += $base ** $_ for 1 .. $exponent;
return 0 if $num > $max;
while ($exponent) {
my $next = $base ** $exponent;
return 1 if $next == $num;
$num -= $next if $num > $next;
$max -= $next;
return 0 if $num > $max;
}
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.