DEV Community

Simon Green
Simon Green

Posted on

1

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

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)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay