28
MarCalculation of Armstrong Number in Python
Armstrong Numbers in Python is an interesting concept for developers who want to explore number manipulation and mathematical operations. Imagine having the ability to check if a number equals the sum of its digits each raised to the power of the number of digits, demonstrating the use of loops, conditionals, and mathematical expressions effectively. Armstrong Numbers provides a practical way to understand number properties and validate conditions dynamically, enhancing your problem-solving skills.
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: |
Python Program to check Armstrong Number
def is_armstrong(num):
num_str = str(num)
num_digits = len(num_str)
total = 0
for digit in num_str:
total += int(digit) ** num_digits
return total == num
num1 = 407
if is_armstrong(num1):
print(num1, "is an Armstrong number.")
else:
print(num1, "is not an Armstrong number.")
num2 = 372
if is_armstrong(num2):
print(num2, "is an Armstrong number.")
else:
print(num2, "is not an Armstrong number.")
Output
407 is an Armstrong number.
372 is not an Armstrong number.
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 is evaluated to the given number, then it isanArmstrongnumber;otherwise, it is not.
Output
407 is an Armstrong number.
372 is not an Armstrong number.
2. Python program to check if a number is an Armstrong number in 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
6. Check Armstrong Number Using List Comprehension
# Function to check if a number is an Armstrong number using list comprehension
def is_armstrong(num):
"""
Function to check whether a given number is an Armstrong number.
:param num: Integer number to check
:return: True if the number is Armstrong, False otherwise
"""
power = len(str(num)) # Get the number of digits
return num == sum(int(digit) ** power for digit in str(num)) # List comprehension
# Driver code
if __name__ == "__main__":
# Test cases
numbers = [153, 9474, 370, 1253]
for num in numbers:
print(f"{num} is Armstrong: {is_armstrong(num)}")
Explanation
- Function Definition: Compares the original number with the sum of its digits raised to the power of its length.
- List Comprehension: Efficiently computes the required sum in one line.
- Driver Code: Ensures code runs only when executed directly.
- Output Logic: Iterates through the list and prints Armstrong status.
Output
153 is Armstrong: True
9474 is Armstrong: True
370 is Armstrong: True
1253 is Armstrong: False
Read More: List Comprehension in Python |
7. Check Armstrong Number Using map() and lambda
# Function to check if a number is an Armstrong number using map() and lambda
is_armstrong = lambda num: num == sum(map(lambda x: int(x) ** len(str(num)), str(num)))
# Driver code
if __name__ == "__main__":
# Test cases
numbers = [407, 9475]
for num in numbers:
print(f"{num} is Armstrong: {is_armstrong(num)}")
Explanation
- Lambda Function:The inline function checks the Armstrong number.
- map() Usage: Raises each digit to the power of digit count.
- sum() Function: Adds the powered digits.
- Conditional Check: Compares the sum with the original number.
Output
407 is Armstrong: True
9475 is Armstrong: False
Read More: |
8. Python program to check if a number is an Armstrong number without using the power function
- Manual Exponentiation: Instead of using pow(), we use a loop to multiply the digit by itself n times.
- Efficient Calculation: The function iterates through the digits and computes the sum using basic arithmetic, avoiding recursion.
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 without using pow()
while n > 0:
digit = n % 10
power = 1
# Compute digit^numDigits manually
for _ in range(numDigits):
power *= digit
sum += power
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.")
Output
407 is an Armstrong number.
372 is not an Armstrong number.
9. Python program to check if a number is an Armstrong number Using string manipulation
- String Conversion: Convert the number to a string to easily extract each digit.
- List Comprehension for Calculation: Use a compact one-liner to compute the sum of each digit raised to the required power.
def isArmstrong(num):
num_str = str(num) # Convert number to string
numDigits = len(num_str) # Count the number of digits
# Compute sum of digits raised to the power of numDigits
total = sum(int(digit) ** numDigits for digit in num_str)
# Check if num is an Armstrong number
return total == num
num1 = 153
if isArmstrong(num1):
print(num1, "is an Armstrong number.")
else:
print(num1, "is not an Armstrong number.")
num2 = 123
if isArmstrong(num2):
print(num2, "is an Armstrong number.")
else:
print(num2, "is not an Armstrong number.")
Output
153 is an Armstrong number.
123 is not an Armstrong number.
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: |
Armstrong Numbers in Different Number Systems
Checking Armstrong Numbers in Binary, Octal, or Hexadecimal
Armstrong Numbers in Binary
- Convert the number to binary format.
- Extract each binary digit and count the total digits.
- Calculate the sum of each digit raised to the power of the total digits.
- If the sum matches the original number, it is an Armstrong number in binary.
Armstrong Numbers in Octal
- Convert the number to octal format.
- Extract the octal digits and count them.
- Compute the sum of each digit raised to the power of the total number of digits.
- If the sum equals the original number, it is an Armstrong number in octal.
Armstrong Numbers in Hexadecimal
- Convert the number to hexadecimal format.
- Extract each hexadecimal digit and determine the total number of digits.
- Calculate the sum of each digit raised to the power of the total digits.
- If the computed sum matches the original number, it is an Armstrong number in hexadecimal.
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.