21
NovCalculation of Armstrong Number in Python
Armstrong Number in Python
What is an Armstrong Number?
- An Armstrong Number is a type of number in which the sum of its digits, each raised to the power of the number of digits, equals the number itself.
- It is also known as a Narcissistic number.
- Armstrong Numbers allows you to verify if a number meets this specific criterion, enabling interesting mathematical explorations and coding exercises.
- You can check if a number is an Armstrong Number by summing up its digits raised to the appropriate power and comparing it to the original number.
- For example, 153 is an Armstrong Number because 13 + 53 + 33 = 153.
- Understanding and identifying Armstrong Numbers provides a practical way to work with loops, conditionals, and mathematical operations, making your code more dynamic and enhancing your problem-solving skills.
Read More: Top 50 Python Interview Questions and Answers |
Mathematical Representation of Armstrong Number
An Armstrong Number of n digits is when the sum of its digits, each raised to the power of the total number of digits, equals the number itself:
abcd… = an + bn + cn + dn + …
- Here, you take each digit (a, b, c, d, …) of the number and raise it to the power of the total number of digits (n).
- For example, if you have a 3-digit number like 370:
370 = 33 + 73 + 03 = 27 + 343 + 0 = 370
This shows that 370 is an Armstrong Number.
Read More: |
Approaches to Check Armstrong Number in Python
1. Digit by Digit Sum Approach to Check for Armstrong Number
import math
def isArmstrong(num):
n = num
numDigits = 0
sum = 0
# Find number of digits in num
while n > 0:
n //= 10
numDigits += 1
n = num
# Calculate sum of digits raised to the power of numDigits
while n > 0:
digit = n % 10
sum += math.pow(digit, numDigits)
n //= 10
# Check if num is Armstrong number or not
if sum == num:
return True
return False
num1 = 407
if isArmstrong(num1):
print(num1, "is an Armstrong number.")
else:
print(num1, "is not an Armstrong number.")
num2 = 372
if isArmstrong(num2):
print(num2, "is an Armstrong number.")
else:
print(num2, "is not an Armstrong number.")
Explanation
- In the above code, first of all, in the isArmstrong() function, we have found the number of digits in the given number and stored it in the numDigits variable.
- Then, we extracted each digit from the given numbers num1 and num2, raised it to the power of the number of digits, and added it to the sum variable.
- If the sum evaluates to the given number, then it is an Armstrong number, else it is not.
Output
407 is an Armstrong number.
372 is not an Armstrong number.
2. Using the return statement
def is_armstrong_number(number):
return sum(int(digit)**len(str(number)) for digit in str(number)) == number
number = 1634
if is_armstrong_number(number):
print(f"{number} is an Armstrong number")
else:
print(f"{number} is not an Armstrong number")
Explanation
- In the above code, the function is_armstrong_number calculates the sum of each digit raised to the power of the number of digits in the number using a generator expression and the sum() function.
- It then compares this sum to the original number to determine if it's an Armstrong number.
Output
1634 is an Armstrong number
3. Check Armstrong number of n digits using a while loop
number = 54748
# Changing num variable to string
order = len(str(number))
sum = 0
temp = number
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if number == sum:
print(number,"is an Armstrong number")
else:
print(number,"is not an Armstrong number")
Explanation
- The code checks if the number (54748) is an Armstrong Number.
- It calculates the sum of each digit raised to the power of the number of digits (order).
- If this sum matches the original number, it prints that it is an Armstrong Number; otherwise, it indicates that it is not.
Output
54748 is an Armstrong number
Read More: while loop in Python |
4. Check Armstrong number of n digits using functions
# Function to calculate x raised to the power y
def power(a, b):
if b == 0:
return 1
if b % 2 == 0:
return power(a, b // 2) * power(a, b // 2)
return a * power(a, b // 2) * power(a, b // 2)
# Function to calculate the order of the number
def order(a):
# Variable to store the number
n = 0
while (a != 0):
n = n + 1
a = a // 10
return n
# Function to check whether the given number is an Armstrong number or not
def isArmstrong(a):
n = order(a)
temp = a
sum1 = 0
while (temp != 0):
r = temp % 10
sum1 = sum1 + power(r, n)
temp = temp // 10
# If condition satisfies
return (sum1 == a)
# Driver code
a = 370
print(isArmstrong(a))
a = 1253
print(isArmstrong(a))
Explanation
- In the above code, power(a, b) is a recursive function that calculates the power of a number a raised to the exponent b.
- The order(a) function calculates the order of a number, i.e., the number of digits in it, whereas the Armstrong (a) function checks if the number a is an Armstrong number by summing the powers of its digits and comparing it to the original number.
Output
True
False
Read More: Python Functions |
5. Check Armstrong number of n digits using Recursion
def getSum(num):
if num == 0:
return num
else:
return pow((num % 10), order) + getSum(num // 10)
num = 371
# Order of the input
order = len(str(num))
# Call the function
sum_val = getSum(num)
if sum_val == num:
print('It is an Armstrong number')
else:
print('It is not an Armstrong number')
Explanation
- The code uses a recursive function (getSum) to check if a number is an Armstrong Number.
- It calculates the sum of each digit raised to the power of the total number of digits (order).
- If this sum matches the original number, it prints that it is an Armstrong Number; otherwise, it indicates that it is not.
Output
It is an Armstrong number
Finding Armstrong Numbers within a given range in Python
lower = 100
upper = 1000
for num in range(lower, upper + 1):
# order of number
order = len(str(num))
# initialize sum
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
if num == sum:
print(num)
Explanation
- The code finds and prints all Armstrong Numbers within a specified range (100 to 1000).
- For each number, it calculates the sum of its digits raised to the power of the number of digits (order).
- If the sum matches the original number, it prints the number as an Armstrong Number.
Output
153
370
371
407
Python Program to Find Armstrong Number in an Interval by Importing Math Module
import math
first, second = 1500, 10000
def is_Armstrong(val):
armstrong_sum_value = 0
temp_list = [int(d) for d in str(val)]
for i in range(0, len(temp_list)):
armstrong_sum_value = armstrong_sum_value + math.pow(temp_list[i], len(temp_list))
if armstrong_sum_value == val:
print(str(val) + ", ", end="")
for i in range(first, second + 1):
is_Armstrong(i)
Explanation
- The code finds and prints all Armstrong Numbers within a range (1500 to 10000).
- The is_Armstrong function calculates the sum of each digit raised to the power of the total number of digits using the math.pow function.
- If this sum equals the original number, it prints the number as an Armstrong Number.
Output
1634, 8208, 9474,
Read More: Modules in Python |
Practical Examples and Use Cases of Armstrong Number
- Error Detection: Armstrong numbers can be used in error detection techniques, especially in data transmission and storage systems, where ensuring data integrity is crucial.
- Security: Armstrong numbers can serve as part of encryption keys or hash functions, enhancing security measures by introducing complexity and randomness into cryptographic systems.
- Data Analysis: Armstrong numbers can be used as keys in databases or as markers in datasets to categorize or filter data based on specific criteria.
- Testing Algorithms: Armstrong numbers provide a useful benchmark for testing and evaluating algorithms, especially those related to number theory and mathematical operations.
- Performance Testing: Armstrong numbers can be utilized in performance testing scenarios to evaluate the computational efficiency of algorithms or systems.
- Puzzle and Game Design: Armstrong numbers can be incorporated into puzzle and game design to create challenges or quests that require players to identify or generate Armstrong numbers.
Read More: |
Summary
Armstrong Numbers in Python are numbers that equal the sum of their digits, each raised to the power of the total number of digits. This concept is useful for practicing number manipulation using loops, conditionals, and mathematical operations. The tutorial covers different methods, such as digit-by-digit sum, recursion, and functions, to identify Armstrong Numbers and find them within specified ranges, demonstrating various programming patterns and techniques.To learn more about Python concepts and by using Python, you start your career as a data scientist. Think about joining ScholarHat's Data Science with Python Certification Course.