DEV Community

Daniel Mantovani
Daniel Mantovani

Posted on

2 2

Perl Weekly Challenge #79,Task #1

Task: Count Set Bits

You are given a positive number $N. Write a script to count the total numbrer of set bits of the binary representations of all numbers from 1 to $N and return $total_count_set_bit % 1000000007.

Proposed Answer:

Note that perl already has the capability to get a binary expression of an integer, just using the sprintf formatter %b, as in

my $binary_string = sprintf("%b", $number);

We need to count how many "1"s are in the binary representation. There are many ways to do that in perl. We will use the return value of the transliteration internal function of perl (tr):

$amount_of_ones = $binary_string =~ tr/1//;

This will efectively remove all "1"s from our string, but most important, will return a scalar with the amount of substitutions done (i.e, number of 1s in the binary representation)

Also we are supposed to truncate to a modulo 1,000,000,007 integer on every addition, probably avoiding any overflows on perl arithmetic for 32 bit perls (that number is a prime number often used for that purpose).

So with all these considerations, our script will just be:

use strict;
use warnings;
use v5.20;

my $big_prime           = 1_000_000_007;
my $total_count_set_bit = 0;

for my $n (1 .. shift) {    # or $ARGV[0]
  $total_count_set_bit += sprintf("%b", $n) =~ tr/1//;
  $total_count_set_bit %= $big_prime;
}

say $total_count_set_bit;

As an example, you can use the script like this:

$> perl ch-1.pl 12345678
143433315
$> _

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay