Python Program to Get Sum of N Armstrong Number
Last Updated :
09 Jan, 2023
Given a number N, determine the sum of the first N Armstrong numbers using Python.
Example:
Input : 11
Output : 568
First 11 Armstrong numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, lies to, 370
Their summation is 578
Method 1: Using Iterative methods
- Create a while loop that breaks when the desired number of Armstrong numbers is found.
- At each iteration, the current value will be incremented by 1.
- The idea is to first count the number of digits present in the current number.
- Let us assume the number of digits be d. For every digit x in the current number, compute x**d. If the sum of all such values is equal to the current number then add that element to the result.
- Finally, return the result.
Python3
def order(x):
return len ( str (x))
def isArmstrong(x):
k = order(x)
cur = x
sum1 = 0
while (cur ! = 0 ):
r = cur % 10
sum1 = sum1 + int (r * * k)
cur = cur / / 10
return (sum1 = = x)
def getSumOfArmstrong(n):
cur = 1
result = 0
cur_elems = 0
while cur_elems ! = n:
if isArmstrong(cur):
result + = cur
cur_elems + = 1
cur + = 1
return result
print (getSumOfArmstrong( 11 ))
|
Output:
568
Complexity Analysis:
Let n be the Nth Armstrong number..
Time Complexity: O(n * len(n))
Space Complexity: O(1)
Method 2: Using recursion method
Instead of using the iterative approach, we can use a recursive approach to check whether the number is Armstrong number or not and also to find order of a number.
We will pass the length of the function and the number itself as parameters to the recursive function.
In each recursive call it will find the digit present in the units place raised to the order of number and calls the function again for the remaining digits excluding the units digit.
Python3
def order(x):
if x / / 10 = = 0 :
return 1
return 1 + order(x / / 10 )
def isArmstrong(x, order):
if x = = 0 :
return 0
if x ! = 0 :
return int ( pow (x % 10 , order)) + isArmstrong(x / / 10 , order)
def getSumOfArmstrong(n):
cur = 1
result = 0
cur_elems = 0
while cur_elems ! = n:
if isArmstrong(cur, order(cur)) = = cur:
result + = cur
cur_elems + = 1
cur + = 1
return result
print (getSumOfArmstrong( 11 ))
|
Output:
568
Complexity Analysis:
Let n be the Nth Armstrong number..
Time Complexity: O(n * len(n))
Space Complexity: O(n) (For recursive call stack)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...