What are happy or unhappy digits in python?
To find out if the choice is happy, replace the amount with the entire of the squares of its digits. Repeat the maneuver till either the amount equals one or loops endlessly very terribly cycle that doesn't embody one. once the maneuver ends with one then vary the number the amount is pictured as a cheerful selection, otherwise, its associate sad vary.
Let's perceive by associate degree example:
Number = 82
8*8+ 2*2 = 68
6*6 + 8*8 = 100
1*1 + 0*0 +0*0 = 1
Algorithms of happy or unhappy digit?
STEP 1: HappyNumber() determines whether or not or not a given selection is happy or not.
If the number is greater than zero, then calculate remainder rem by dividing the number by 10.
Calculate sq. of rem and add it to a variable total.
Divide selection by 10.
Repeat the steps from a to c till the overall of the sq. of all digits gift in selection has been calculated.
Finally, come the overall.
STEP 2: define and initialize variable num.
STEP 3: define a variable result and initialize it with a worth of num.
STEP four: If the result is neither up to 1 nor four then, produce a call to HappyNumber().
STEP 5: Otherwise, if the result is up to 1 then, the given selection may well be a contented selection.
STEP 6: If the result is up to four then, the given selection is not a cheerful selection.
Program in python
Create a function and performance name is HappyNumber and take one argument as num within the type of input
def HappyNumber(num):
Initialize add and remainder as the variable is zero
rem = sum = 0;
Calculates the sum of squares of digits and apply the logic and conditions
while(num > 0):
rem = num%10;
sum = sum + (rem*rem);
num = num//10;
return sum;
Take input within the type of num variable
num = int(input(“enter the number”)
result = num
while(result != 1 and result != 4):
result = HappyNumber(result);
Happy range always ends with 1 and condition is true then print happy range different wise print unhappy digits
if(result == 1):
print(str(num) + " is a happy number");
The unhappy number ends in a cycle of repeating numbers which contain 4
elif(result == 4):
print(str(num) + " is not a happy number");
The final output is :
Enter the amount = 82
82 may be a happy digits
Enter the amount = 36
36 isn't happy dgits
#somaymangla #somaymangla #somaymangla
#somaymangla
#somaymangla
Author
No comments:
Post a Comment