DEV Community

dev.to staff
dev.to staff

Posted on

6 3

Daily Challenge #294 - Sum and GCD Practice

Given the sum and greatest common divisor of two numbers, return those two numbers in ascending order. If the numbers do not exist, return -1 or your language's equivalent.

Examples

Given sum = 12 and gcd = 4...

solve(12,4) = [4,8]. The two numbers 4 and 8 sum to 12 and have a gcd of 4.

solve(12,5) = -1. No two numbers exist that sum to 12 and have gcd of 5.

solve(10,2) = [2,8]. Note that [4,6] is also a possibility but we pick the one with the lower first element: 2 < 4, so we take [2,8].

Tests

solve(12,4)
solve(16,8)
solve(21,7)

Good luck!


This challenge comes from KenKamau on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

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 (3)

Collapse
 
_bkeren profile image
''

If there is a combination, minimum number = gcd itself, the other number = sum - gcd

const solve = (sum,gcd) => (sum-gcd) % gcd ? -1 : [gcd,sum-gcd]
Collapse
 
willsmart profile image
willsmart

Well spotted!

Collapse
 
peter279k profile image
peter279k

Here is my simple solution with Python:

def solve(s,g):
    answer = []
    original_s = s
    while s % g == 0:
        if int(s / g) <= g:
            answer.append(g)
            break

        s = int(s / g)

    if s != original_s and len(answer) == 0:
        answer.append(g)

    if len(answer) == 0:
        return -1

    answer.append(original_s - answer[0])

    return tuple(answer)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

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

Okay