Peter
Peter Campbell Smith

Count numbers and bombs

Weekly challenge 126 — 16 August 2021

Week 126: 16 Aug 2021

Task 1

Task — Count numbers

You are given a positive integer $N. Write a script to print count of numbers from 1 to $N that don’t contain digit 1.

Examples

Example
Input: $N = 15
Output: 8
    There are 8 numbers between 1 and 15 that don't 
	contain digit 1:
    2, 3, 4, 5, 6, 7, 8, 9.
Input: $N = 25
Output: 13
    There are 13 numbers between 1 and 25 that don't 
	contain digit 1:
    2, 3, 4, 5, 6, 7, 8, 9, 20, 22, 23, 24, 25.

Analysis

I did not submit a solution at the time, but have written this later.

This is an easy one-liner. It deals with $N = a million in just a couple of seconds.

Try it 

Try running the script with any input:



example: 12345

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2021-08-16
use utf8;     # Week 126 - task 1 - Count numbers
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

count_numbers(15);
count_numbers(25);
count_numbers(1000000);

sub count_numbers {
    
    my ($n, $c);
    
    $n = shift;
    $c += $_ =~ m|1| ? 0 : 1 for 1 .. $n;
    
    say qq[\nInput:  \$N = $n];
    say qq[Output: \$count = $c];
}

Output


Input:  $N = 15
Output: $count = 8

Input:  $N = 25
Output: $count = 13

Input:  $N = 1000000
Output: $count = 531440

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain