Pernicious numbers
... are positive integers which have a prime number of ones in their binary representation, and they can presumably have any number of zeroes as well.
Perl conveniently has the $binary = sprintf('%b', $n) construct which quickly gives us the binary representation of $n, and we can then count the 1s like this:
@ones = $binary =~ m|1|g;
This rather counterintuitive statement works because the m|| returns a list of matches which can then be assigned to an array, and the number of elements in the array thus gives the number of matches, or in our case, the number of 1s.
And as we've dealt with the generation of primes often in the last few weeks I took the lazy way out and used Math::Prime::Util 'is_prime' to determine whether the count is prime.
Weird numbers
... are defined as those where the sum of the proper divisors (divisors including 1 but not the number itself) is greater than the number, but no subset of those divisors sums to the number.
So this breaks down to three steps:
- Find the proper divisors of n
- Check that their sum is greater than n
- Check that no combination of the divisors sums to n
No comments:
Post a Comment