0

I am trying to find the magic number in this program but I got stuck on this part and am not sure where to go next. I have searched up many ways on the internet but they are all using more complex code that I have not learned yet.

Example 
input 45637
4+5+6+3+7 = 25
2+5 = 7
7 = magic number 

num = int(input("Enter a positive number : "))
ans = 0

while num > 0 or ans > 9:
    digit = num % 10
    num = num//10
    print(digit)
Joe
  • 33
  • 6
  • 1
    You didn't ask a question – DeepSpace Apr 17 '20 at 18:08
  • Look into [my answer on recursive-sum-of-all-the-digits-in-a-number](https://stackoverflow.com/questions/61233330/recursive-sum-of-all-the-digits-in-a-number/61234001#61234001) from 2 days ago or [that one thats closer to what you do](https://stackoverflow.com/a/61236326/7505395) – Patrick Artner Apr 17 '20 at 18:16
  • `print(num%0)` -- except that if this turns up `0`, you need to print `9` instead. This is also called the "digital root" of the number. The digital root of any number in base `k` is `num%k`. If you want to see the mechanics of this process, look up "casting out nines". – Prune Apr 17 '20 at 18:25
  • The thread shouldn't have been closed, because it's not simply an addition of all digits in an integer. It should be opened and edited. – Thaer A Apr 17 '20 at 18:25

2 Answers2

1

Using statements and operators you have already learned as demonstrated in your code, you can use a nested while loop to aggregate the digits from the division remainders into a total as the number for the next iteration of the outer while loop:

num = 45637
while num > 9:
    total = 0
    while num > 0:
        digit = num % 10
        num = num // 10
        total = total + digit
    num = total
print(num)

This outputs:

7
blhsing
  • 91,368
  • 6
  • 71
  • 106
1

One way:

while len(str(ans))>1:
    ans = sum(map(int, str(ans)))

Full code:

num = int(input("Enter a positive number : "))
ans = num

while len(str(ans))>1:
    ans = sum(map(int, str(ans)))

print(ans)

Output for input 45637:

7
Thaer A
  • 2,243
  • 1
  • 10
  • 14