Home

Subtract Product and Sum

math operations in a white paper with a pencil Photo by Chris Liverani

This post is part of the Algorithms Problem Solving series.

Problem Description

This is the Subtract Product and Sum problem. The description looks like this:

Given an integer number n, return the difference between the product of its digits and the sum of its digits.

Examples

Input: n = 234
Output: 15

Input: n = 4421
Output: 21

Solution

For each character, we transform it into an integer value, and then use as part of the multiplication and sum. At the top of the function scope, we define two variables: one for the multiplications and the other for the additions.

After the loop, we just need to return the subtraction between multiplications and additions.

def subtract_product_and_sum(num):
    multiplications = 1
    additions = 0

    for digit in str(num):
        multiplications *= int(digit)
        additions += int(digit)

    return multiplications - additions

Resources

Have fun, keep learning, and always keep coding!

My Twitter and Github

Patreon Become a Patron Coffee icon Buy me a coffee