Armstrong Number in Java: Armstrong Number is an integer such that the sum of the cubes of its digits is equal to the number itself. Armstrong numbers are 0, 1, 153, 370, 371, 407, etc.
Formula to calculate Armstrong Number:
wxyz = pow(w,n) + pow(x,n) + pow(y,n) + pow(z,n)
Example:
Let’s look at 371 as an example to understand why it’s an Armstrong number.
371 = 3*3*3 + 7*7*7 + 1*1*1 = 27 + 343 + 1 = 371
Write a Java program to check if a given number is Armstrong. If the number is an Armstrong then display it is an Armstrong number else display it is not an Armstrong number.
Here is the source code of the Java Program to Check If a Given Number is ArmStrong Number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
import java.util.Scanner; public class ArmStrong { public static void main(String[] args) { int n, count = 0, a, b, c, sum = 0; Scanner s = new Scanner(System.in); System.out.print("Enter a number:"); n = s.nextInt(); a = n; c = n; while(a > 0) { a = a / 10; count++; } while(n > 0) { b = n % 10; sum = (int) (sum+Math.pow(b, count)); n = n / 10; } if(sum == c) { System.out.println(c+ " is an Armstrong number"); } else { System.out.println(c+ " is not an Armstrong number"); } } }
1. Take the number as an input and store it in the variable “n”.
2. Use modulos and division operations along with loops to find the armstrong number.
3. Use if else statements to get the output.
Time Complexity: O(log(n))
O(log(n)) + O(log(n)) = O(log(n))
The above program for checking whether a number is Armstrong or not has a time complexity of O(log(n)) as both the while loop runs for log(n) times because at each iteration the number is divided by 10, where n is the number given as input.
Space Complexity: O(1)
space complexity of the armstrong program is O(1) as no extra variable is taken to store the value. All the variables initialized takes constant O(1) space.
Enter a number: 371 371 is an Armstrong number Enter a number: 150 150 is not an Armstrong number
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Practice BCA MCQs
- Apply for Java Internship
- Practice Programming MCQs
- Apply for Information Technology Internship
- Practice Information Technology MCQs