Armstrong Numbers upto 'n' numbers in JAVA

Armstrong Number in JAVA

Armstrong Number: A number is said to be Armstrong Number, If it is a equal to the sum of its own digits each raised to the power of the number of digits.


Example:
Input                   : 153
No. of Digits       : 3
Sum of digits      : 13 + 53 + 33 = 1 + 125 + 27 = 153
Output                 : It is an Armstrong Number

Input                  : 15
No. of Digits      : 2
Sum of digits     : 12 + 52 = 1 + 25 = 26
Output                : It is not an Armstrong Number

Input                  : 1634
No. of Digits     : 4
Sum of digits    : 14 + 64 + 34 + 44 = 1 + 1296 + 81 + 256 = 1634
Output               : It is an Armstrong Number


Algorithm and Program given below :-

Algorithm :-

  • Input a number
  • Use for loop from 0 to the input number
  • Copy the value of loop variable in another variable
  • Using a string variable convert the integer value into string
  • Store the length of this string in another variable.
  • Using while loop calculate the sum of digits raised with the power of number of digits in a variable say ‘s’.
  • Compare the calculated number with the original number
  • If the numbers are equal print the number.
  • Initialize value of s=0 within the for loop again.
  • Compile and run the program
 
Program :-

import java.io.*;
import java.util.*;
class Armstrong1
{
    public static void main(String args[])
    {
        Scanner in= new Scanner(System.in);
        int n,p,rev,i,l;
        double s=0;
        String str;
        System.out.println("Enter the number");
        n= in.nextInt(); // Enter Number from user
        System.out.println("Armstrong Number from 0 to "+n+" are:-");
        for(i=0;i<=n;i++)
        {
            p=i;
            str= Integer.toString(i);
            l= str.length();
            while(p>0)
            {
                rev= p%10; // extracting last digit of the number
                s=s+Math.pow(rev,l); // Storing digit with respective power
                p=p/10; // extracting quotient of the number
            }
            if(s==i) // checking entered number with cubes of its digits
            {
                System.out.println(i);
            }
            s=0;
        }
    }// end of main method
}// end of class




Video Link of this Program : https://youtu.be/Ldsyc7hfUr4

Follow me on Instagram

All the Best :)
Keep Learning :)

 


Comments

Popular posts from this blog

Frequency of each digit of a number in Java

Trimorphic Number in JAVA

Tri-Automorphic Number in JAVA