How to divide a number in Python

1 min read 275 words

The challenge

Your task is to create functionisDivideBy (or is_divide_by) to check if an integer number is divisible by each out of two arguments.

A few cases:

(-12, 2, -6)  ->  true
(-12, 2, -5)  ->  false

(45, 1, 6)    ->  false
(45, 5, 15)   ->  true

(4, 1, 4)     ->  true
(15, -5, 3)   ->  true

Test cases

Test.describe("Basic Tests")
Test.it("should pass basic tests")
Test.assert_equals(is_divide_by(-12, 2, -6), True)
Test.assert_equals(is_divide_by(-12, 2, -5), False)
Test.assert_equals(is_divide_by(45, 1, 6), False)
Test.assert_equals(is_divide_by(45, 5, 15), True)
Test.assert_equals(is_divide_by(4, 1, 4), True)
Test.assert_equals(is_divide_by(15, -5, 3), True)

Understanding how to solve this

To resolve this problem, we need to understand how to find if a number can be divided without a remainder in Python. This is similar to other mathematical operations you might perform in Python, like finding the intersection of two arrays or converting RGB to Hex .

For this we will use Python’s modulo operator, (%):

10 % 5  # 0
# if we divide 10 by 5, there is no remainder

10 % 3  # 1
# if we divide 10 by 3, there is a remainder of `1`

Therefore, if we say 10 % 5 == 0, the expression will equal True, while the 10 % 3 == 0 will equal False. This is because there is a remainder of 1 in the second instance.

The solution in Python

Option 1:

def is_divide_by(number, a, b):
    # if can divide without remainder
    if number % a ==0 and number % b ==0:
        return True
    else:
        return False

Option 2:

def is_divide_by(number, a, b):
    return not (number%a or number%b)

Option 3:

def is_divide_by(n, a, b):
    return n%a == 0 == n%b
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags