A magic number is that number whose repeated sum of its digits till we get a single digit is equal to 1.
Steps to Check Magic Number in Python
- Take a number as input (num).
- Calculate the sum of digits of the input number.
- Repeat step 2 until we get a single digit.
- If resultant sum is equal to 1 then it is a Magic number else not.
We will calculate the sum of the digits until we get a single-digit number as the sum. To count the number of digits we will use math.log10()+1.
Check Whether a number is a Magic Number in Python
import math num = int(input("Enter a Number \n")) digitCount = int(math.log10(num))+1 sumOfDigits = 0 temp = num #copying num #calculating sum of digits of temp(i.e num) until #sumOfDigits is a single digit while( digitCount > 1): sumOfDigits = 0 while(temp > 0): sumOfDigits += temp%10 temp = temp//10 temp = sumOfDigits #count the digits of sumOfDigits digitCount = int(math.log10(sumOfDigits))+1 #check whether sumOfDigits == 1 if(sumOfDigits == 1): print("Magic number") else: print("Not a magic number")
Output
Enter a Number 65 Not a magic number Enter a Number 1729 Magic number
Find all the Magic Numbers in the interval in Python
import math def magic_number(num): digitCount = int(math.log10(num))+1 sumOfDigits = 0 temp = num #copying num #calculating sum of digits of temp(i.e num) until #sumOfDigits is a single digit while( digitCount > 1): sumOfDigits = 0 while(temp > 0): sumOfDigits += temp%10 temp = temp//10 temp = sumOfDigits #count the digits of sumOfDigits digitCount = int(math.log10(sumOfDigits))+1 #check for sumOfDigits == 1 if(sumOfDigits == 1): print(num) low = int(input("Enter lower interval value \n")) up = int(input("Enter upper interval value \n")) print("Magic numbers between {x} and {y} are".format(x=low,y=up)) for num in range(low,up+1): magic_number(num)
Enter lower interval value 1 Enter upper interval value 100 Magic numbers between 1 and 100 are 10 19 28 37 46 55 64 73 82 91 100
Any doubts then comment below.
please make it that after adding the digits in the number given the answer should be 1
Thanks for the suggestion.