Question
Print Armstrong number in an (Array for Java/ List for Python)
A positive number is called armstrong number if sum of its own digits each raised to the power of the number of digits is equal to number
153
1^3+5^3+3^3=1+125+27=153
153 is an armstrong number
Enter the size of list:10
enter element in given list:
1:30
2:20
3:1
4:153
5:99
6:107
7:19
8:145
9:131
10:3
Elements in given List:
[30, 20, 1, 153, 99, 107, 19, 145, 131, 3]
Armstrong number in given List:
1 153 3
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
Java
Python
Java
import java.util.Scanner;
public class ArmstrongNumberInArray
{
public static void main(String[] args)
{
/* Initialize array */
int [] arr;
int n=0,i=0,temp=0,c=0,r=0,noOfDigits=0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number of elements in the array");
n = sc.nextInt();
arr=new int[n];
System.out.println("Enter numbers in array");
for(i=0;i< n;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Elements entered in Given array");
for(i=0;i< n;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println();
/* printing Armstrong elements in an array */
System.out.println("Armstrong Elements in an array:");
for(i=0;i< n;i++)
{
c=0;
temp=arr[i];
noOfDigits=Integer.toString(temp).length();
while(temp>0)
{
r=temp%10;
temp=temp/10;
c=c+(int)(Math.pow(r,noOfDigits));
}
if(arr[i]==c)
{
System.out.print(arr[i]+" ");
}
}
}
}
Python
li=[]
size=int(input("Enter the size of list:"))
print("enter element in given list:")
for i in range(0,size):
print((i+1),end=":")
li.append(int(input()))
print("Elements in given List:")
print(li)
print("Armstrong number in given List:")
for element in li:
totalDigits=len(str(element))
"""
str(element) converted integer to string
len() gives length of string
so len(str(element)) combined gives total number of digits
"""
sum=0
temp = element
while(temp>0):
digit=temp%10
sum=sum+digit**totalDigits
temp=temp//10
if(sum==element):
print(element,end=" ")