Skip to content

Question 15

What is the output of the following code?

num = 1490414

total = 0
for digit in str(num):
    if int(digit) % 2 != 0:
        total += int(int(digit)**0.5)
    else:
        total -= int(int(digit)**0.5)

print(total)
Solution

Given starting total = 0, iterating through string '1490414':

digit (for loop) int(digit) % 2 != 0? total
digit = '1' int('1') % 2 = 1 != 0 (True) 0 + int(1**0.5)
= 0 + 1
= 1
digit = '4' int('4') % 2 = 0 != 0 (False) 1 - int(4**0.5)
= 1 - 2
= -1
digit = '9' int('9') % 2 = 1 != 0 (True) -1 + int(9**0.5)
= -1 + 3
= 2
digit = '0' int('0') % 2 = 0 != 0 (False) 2 - int(0**0.5)
= 2 - 0
= 2
digit = '4' int('4') % 2 = 0 != 0 (False) 2 - int(4**0.5)
= 2 - 2
= 0
digit = '1' int('1') % 2 = 1 != 0 (True) 0 + int(1**0.5)
= 0 + 1
= 1
digit = '4' int('4') % 2 = 0 != 0 (False) 1 - int(4**0.5)
= 1 - 2
= -1
Note

Exponent/power 0.5 is the same as 1/2 power, which is equal to square root.

\[ a^{\frac{1}{n}} = \sqrt[n]{a} \\ a^{0.5} = a^{\frac{1}{2}} = \sqrt{a} \]
Answer
-1