DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 133

Challenge, My solution

TASK #1 › Integer Square Root

Task

You are given a positive integer $N.

Write a script to calculate the integer square root of the given number.

Please avoid using built-in function.

My solution

So that wikipedia page has enough formulas to get a math nerd very excited. For me it looks a little to complex to understand. So I took a very simple approach. Start from one, and keep counting upwards while the square of the next number is equal or less to the input value.

This seems reasonably efficient for what we are doing. Even finding the integer square root of 10,000,000,000,000,000 only takes a few seconds.

Examples

$ ./ch-1.pl 10
3

$ ./ch-1.pl 27
5

$ ./ch-1.pl 85
9

$ ./ch-1.pl 101
10

Enter fullscreen mode Exit fullscreen mode

TASK #2 › Smith Numbers

Task

Write a script to generate first 10 Smith Numbers in base 10.

My solutions

This turned out to be a bit more complicated than I thought. I'm glad the Wikipedia page had examples, otherwise I would have submitted a faulty solution.

I have two functions for this task. The _digit_sum function takes a number, and calculates the sum of the digits. So 265 is 2 + 6 + 5 = 13. The second function is _prime_factor_sum. This gets the prime factors that make up the number. If the number is a prime, we return -1 to ensure equality is not matched. Once we have the primes we get the sum of the sum of the digits of the prime multipled by its factor. So 265 is 5¹ × 53¹. This results in 5 × 1 + (5 + 3) × 1 = 5 + 8 = 13.

Like with the first task, I have a counter that starts at 2 and keeps adding until I have found the first 10 Smith numbers. Once found, I display the numbers.

Examples

$ ./ch-2.pl 
4, 22, 27, 58, 85, 94, 121, 166, 202, 265
Enter fullscreen mode Exit fullscreen mode

Top comments (0)