DEV Community

Simon Green
Simon Green

Posted on

2 2

Weekly Challenge 141

Challenge, My solutions

TASK #1 › Number Divisors

Task

Write a script to find lowest 10 positive integers having exactly 8 divisors.

My solutions

The main part of this challenge is calculating the number of divisors a given number has. This is one of those cases where you can over-optimize the code for no real benefit. My function divisors assumes that a number has two divisors (1 and itself) and then goes from 2 to half the number to see if there is any other divisors. A special case is made for one, which only has one divisor.

Once that part is done, the main function has an list called solutions, and set number to 1. It then increments number and adds it to the solutions list if it has eight divisors, continuing until we have 10 numbers.

The Perl solution is a transliteration of the Python code.

Examples

$ ./ch-1.py
24, 30, 40, 42, 54, 56, 66, 70, 78, 88

$ ./ch-1.pl
24, 30, 40, 42, 54, 56, 66, 70, 78, 88
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Like Numbers

Task

You are given positive integers, $m and $n.

Write a script to find total count of integers created using the digits of $m which is also divisible by $n.

Repeating of digits are not allowed. Order/Sequence of digits can’t be altered. You are only allowed to use (n-1) digits at the most. For example, 432 is not acceptable integer created using the digits of 1234. Also for 1234, you can only have integers having no more than three digits.

My solutions

In Python I use itertools' combinations function to generate a list of all combinations. I then use a for loop to count the number of combinations that are divisible by n.

Perl doesn't have a built in combination function, so I took a slight different tack with this task. I basically used a binary switch to generate a list of combinations using map { substr( $m, $_, 1 ) } grep { $i & 2**$_ } ( 0 .. $l - 1 ) where $l is the length of the first number ($m) and $i is between 1 and 2$l - 2.

Examples

$ ./ch-2.py 1234 2
9

$ ./ch-2.py 768 4
3

$ ./ch-2.pl 1234 2
9

$ ./ch-2.pl 768 4
3
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay