Все числа армстронга java

Java Program to find Armstrong numbers with Example

Armstrong number Example in Java
How to check if a number is an Armstrong number or not? or write a Java program to find Armstrong’s number? This is a common Java interview question asked on-campus interviews and fresher-level interviews. This is also a popular Java programming exercise on various schools, colleges, and computer courses to build programming logic among Students. An Armstrong number is a 3 digit number for which the sum of cube of its digits is equal to the number itself.

One of the popular examples of the Armstrong number is 153 as 153= 1+ 125+27 which is equal to 1^3+5^3+3^3 which is equal to the sum of cube of its digits 1, 5, and 3

One more example of the Armstrong number is 371 because it is the sum of 27 + 343 + 1 which is equal to 3^3 + 7^3 + 1^3. In this Java program example, we will see a complete code example of a Java program to check if any 3 digit number is an Armstrong number or not.

If you are going for a Java interview, then be prepared for some follow-up questions like finding prime numbers, or finding Armstrong numbers of more than 3 digits.

Btw, good knowledge of essential programming concepts, operators, algorithms, data structure, and logic is important for any software engineer, particularly to do well on technical interviews. If you are preparing for a tech interview then you should double down on these topics.

If you need recommendations to refresh your Data Structure and algorithm skills then I highly recommend checking out Data Structures and Algorithms: Deep Dive Using Java course on Udemy. It’s a hands-on course and covers all essential data structures. It’s also very affordable and you can get in just $10 on Udemy flash sales which happen every now and then.

How to check if a number is Armstrong number in Java

Here is the complete code for checking if a number is an Armstrong number or not. It uses a method called isArmstrong(int number) to implement the logic for checking if a number is Armstrong nor not.

Btw, this is not the same program as print all Armstrong numbers between 0 and 999 but you can use this logic to solve that question as well. All you need to do is loop till 1000 and check if the number is Armstrong or not. If yes then print otherwise move to the next number.

These programs will help you to build the coding sense required to solve coding problems on interviews and your day-to-day life. It’s also one of the important skills to map a new coding problem into an already known one and essential to pass the coding interview on companies like Google, Facebook, Amazon, and Microsoft.

If you are preparing for those companies then I also suggest you go through Grokking the Coding Interview: Patterns for Coding Questions on Educative, an interactive portal for coding interviews to learn some 16 useful coding patterns like Sliding Window, Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve zones of frequently asked coding problems.

Читайте также:  Java выполнить строку кода

How to check if a number is Armstrong number in Java

Java Program to Find Armstrong Number

import java.util.Scanner; /** * Simple Java Program to check or find if a number is Armstrong number or not. * An Armstrong number of three digit is a number whose sum of cubes of its digit is equal * to its number. For example 153 is an Armstrong number * of 3 digit because 1^3+5^3+3^3 or 1+125+27=153 * @author Javin */ public class ArmstrongTest< public static void main(String args[]) < //input number to check if its Armstrong number System.out.println("Please enter a 3 digit number to find if its an Armstrong number:"); int number = new Scanner(System.in).nextInt(); //printing result if(isArmStrong(number))< System.out.println("Number : " + number + " is an Armstrong number"); >else< System.out.println("Number : " + number + " is not an Armstrong number"); > > /* * @return true if number is Armstrong number or return false */ private static boolean isArmStrong(int number) < int result = 0; int orig = number; while(number != 0)< int remainder = number%10; result = result + remainder*remainder*remainder; number = number/10; > //number is Armstrong return true if(orig == result)< return true; > return false; > > Output: Please enter a 3 digit number to find if its an Armstrong number: 153 Number : 153 is an Armstrong number Please enter a 3 digit number to find if its an Armstrong number: 153 Number : 153 is an Armstrong number Please enter a 3 digit number to find if its an Armstrong number: 371 Number : 371 is an Armstrong number

That’s all on How to check if a number is Armstrong in Java. It’s a pretty simple Java program and if you look closely it just gets digit by digit by using the remainder operator and reduces the number by 1 digit after dividing it by 10. Let me know if you find any bug on this Java program to check for the Armstrong number.

  • How to reverse a String in place in Java? (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to find a missing value from an array containing 1 to 100? (solution)
  • How to check if the given string is palindrome or not in Java? (solution)
  • How to find the highest occurring word from a text file in Java? (solution)
  • 100+ Data Structure and Algorithms Problems (solved)
  • 10 Books to learn Data Structure and Algorithms (books)
  • How to check if two given Strings are Anagram in Java? (solution)
  • 10 Data Structure and Algorithms course to crack coding interview (courses)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to count vowels and consonants in a given String in Java? (solution)
  • How to remove duplicate characters from String in Java? (solution)
  • How to check if a given number is prime or not? (solution)
  • 10 Free Courses to learn Data Structure and Algorithms (courses)
  • 101 Coding Problems and few tips for Tech interviews (tips)
  • When to use ArrayList vs LinkedList in Java? (answer)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • How to convert a linked list to an array in Java? (example)
  • My favorite free courses to learn data Structure in-depth (FreeCodeCamp)
  • Top 5 Books to Learn Data Structure and Algorithms (books)
  • How to count the number of leaf nodes in a given binary tree in Java? (solution)
  • Top 5 Books for Programming and Coding Interviews (books)
  • How to find the first and last element of a linked list in Java? (solution)
  • How to search elements inside a linked list in Java? (solution)
  • What is the difference between LinkedList and ArrayList in Java? (answer)
  • 21 String coding Problems from Technical Interviews (questions)
  • How to reverse words in a given String in Java? (solution)
Читайте также:  Html load png file

P. S. — If you are preparing for a programming job interview, then you must prepare for an all-important topic like data structure, String, array, etc. One course which can help you with this task is the Grokking the Coding Interview: Patterns for Coding Questions course. It contains popular coding interview patterns which will help you to solve most of the problems in your coding interviews.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Efficient Armstrong Number generation in Java

shamily/ArmstrongNumbers

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Armstrong Numbers — Fast Algorithms

The task is to generate Armstrong Numbers from 1 up to the length of N decimal digits.

Armstrong number (aka Narcissistic number) of length N digits is a number which is equal to the sum of its digits each in power of N. For example: 153 = 1^3 + 5^3 + 3^3 = 3 + 125 + 27 = 153

There is an obvious bruteforce algorithms that:

  1. Pre-generation of all powers i^j, where i is a digits, and j is possible length from 1 to N — this is necessary for all solutions
  2. For each integer i from 1 to K
  3. Divides i by digits
  4. Calculate power of each digit
  5. Sum up those powers
  6. If this sum is equal to i — add it to the result list
Читайте также:  Javascript functions with return

It can be improved by parallel calculation of sum of digit powers to the number generation.

Hash Approach — Divide At Impera

There is another interesting idea of bruteforce approach improvement.

  1. Divide a number for two equal parts. In case of an odd N first part will be a bit longer. For example, if N=7, the number will be divide like XXXXYYY, where XXXX the first part (4 decimal digits), and YYY the second part with 3 digits.
  2. Generate all integers i of the second part (in our example there will be integers from 001 to 999).
  3. Calculate p equal to sum of digits in power of N.
  4. Add to some hash the following pair . For example, for i=725, p=7^7+2^7+5^7=901796. We add pair .
  5. Generate all integers i of the first part without leading zeros (in our example there will be integers from 1000 to 9999).
  6. Calculate p equal to sum of digits in power of N.
  7. Check if hash has a key of (i*10^(N/2)-p). For example, i=1741, thus p=1^7 + 7^7 + 4^7 + 1^7=839929. We look for key (1741000 — 839929) = (901071). OMG! It exists.
  8. In case that key exists we unite the Armstrong number from two parts and add it to the result list. 1741000 + 725 = 1741725

One addition, is that we cannot store simply (key, value), we need to store multiple values, for example to be able to generate 370 and 371.

We may note that for each multi-set of digits, like [1, 1, 2, 4, 5, 7, 7] there is only one sum of powers, which in its turn may either be or be not represented by the digits from set. In the example 1^7 + 1^7 + 2^7 + 4^7 + 5^7 + 7^7 + 7^7 = 1741725, which can be represented by the digits and thus is an Armstrong number.

We may build an algorighm basing on this consideration.

  1. For each number length from 1 to N
  2. Generate all possible multi-sets of N digits
  3. For each multi-set calculate sum of digits^N
  4. Check if it»s possible to represent the number we got on step 4 with the digits from the multi-set
  5. If so — add the number to the result list

Complexity assestment The number of cases calculated for each length N is equal to the number of combinations (N + 9, 9) = (N+9)!/(9!N!). Thus for all Ns less than 10 we will generate 92,377 cases. For N

Let’s compare the algorithms performance for different numbers of length N. I did the tests with my MacBook Pro.

Algorithm int (N <10) long (N <20) BigInteger (N <40)
Brute Force ~55 seconds few thousand years N/A
Improved Brute Force ~3.7 s ~300 years N/A
Hash Approach 50 ms OutOfMemoryException N/A
Multi-set Approach 15 ms ~1.1 s N/A
Multi-set Improved 11 ms ~550 ms N/A
Multi-set Improved BigInteger ~100 ms ~5.5 s ~ 0.5 hours

Clear win of the multi-set algorithm!

About

Efficient Armstrong Number generation in Java

Источник

Оцените статью