π Day 34/150 – Armstrong Number in Python
An Armstrong number is a number that is equal to the sum of its own digits raised to the power of total digits.
Example: 153 = 1³ + 5³ + 3³ = 153
Let’s explore different ways to check Armstrong number in Python π
πΉ Method 1 – Using while Loop
n = 153 temp = n digits = len(str(n)) total = 0 while n > 0: digit = n % 10 total += digit ** digits n //= 10 if temp == total: print("Armstrong Number") else: print("Not Armstrong Number")
✅ Best numeric method.
πΉ Method 2 – Taking User Input
n = int(input("Enter a number: "))
temp = n
digits = len(str(n))
total = 0
while n > 0:
digit = n % 10
total += digit ** digits
n //= 10
print("Armstrong Number" if temp == total else "Not Armstrong Number")
✅ Useful for dynamic programs.
πΉ Method 3 – Using for Loop + String
n = 153 digits = len(str(n)) total = sum(int(i) ** digits for i in str(n)) if n == total: print("Armstrong Number") else: print("Not Armstrong Number")
✅ Short and clean method.
πΉ Method 4 – Using Function
def is_armstrong(n): digits = len(str(n)) total = sum(int(i) ** digits for i in str(n)) return n == total print(is_armstrong(153))
✅ Reusable for projects.
π Example Output
For 153
Armstrong Number
π― Best Method?
✔ while loop → best for logic building
✔ for loop + string → shortest method
✔ function → reusable and clean


0 Comments:
Post a Comment