Python Code Example: calculate cross sum (iterative and recursive)

Iterative version

This is a Python function crossSum that calculates the cross sum of a given number n. The cross sum is calculated as the sum of its digits.

The function uses a while loop that continues until n is equal to 0. In each iteration of the loop, the rightmost digit of n is extracted using the modulo operator (% 10) and added to the total variable. The total is then converted to an integer using the int function. The n is then updated to be n divided by 10 (integer division), which discards the rightmost digit and shifts the rest of the digits to the right. This process continues until n becomes 0.

The final value of total is then returned as the result of the function.

In the code, crossSum is called with the argument 123, and the result is printed, which is 6.

def crossSum(n):
    total = 0
    while 0 != n:
        total = int(total + (n % 10))
        n = n / 10

    return total


print(crossSum(123))
Output
6

Recursive version

This is a Python function crossSum that calculates the cross sum of a given number n. The cross sum is calculated as the sum of its digits.

The function uses recursion to extract and sum up the digits of the input number n. The base case of the recursion is if n is less than or equal to 9, in which case n is returned as the result. In other cases, the rightmost digit of n is extracted by taking the modulo of n with 10 and added to the result of calling the crossSum function with n divided by 10 (integer division). This process continues until n becomes less than or equal to 9.

In the code, crossSum is called with the argument 555, and the result is printed, which is 15.

def crossSum(n):
    return n if n <= 9 else (n % 10) + int(crossSum(n / 10))


print(crossSum(555))
Output
15