Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Armstrong number in java with recursion

I have to check whether a number is an Armstrong number or not, using a recursive method

public class ArmStrong {
    public static void main(String[] args){
        System.out.println(isArm(407,0,0));
    }
    static boolean isArm(int n,int last,int sum){
        if(n <= 0 ){
            if(sum == n){
                return true;
            }else{
                return false;
            }
        }
        return isArm(n/10,n%10,sum + last*last*last);
    }
}

When I debug, in the last call of isArm when n is 4, the base statement is skipped.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code will instantly jump to the answer (if (n <= 0)) before applying the cube of the last digit.

For example, trivially, let’s try 9, which obviously isn’t armstrong.

Your code will first check if 9 is 0 – it’s not. So, we recurse, which will go with self(0, 9, 0+0). The next run is supposed to then recurse once more, so that the sum + last*last*last can actually get some cubing done. But it’ll never get there – n is 0, so, you jump into the if.

As your variable name kinda gives away last is referring to the digit that the previous run lopped off, and yet you aren’t cubing it.

The solution is to simply get the cubing in before checking if n is null:

The first thing your method should do is

sum += last*last*last;

Then, the second problem shows up: This correctly calculates your sum to be 407, but you check this against n, which is, obviously, 0 – you are ‘destroying’ n as you go through. One trivial way to solve that is to pass the original n, unmolested, through, as a 4th parameter. I’ll leave that as an exercise for the reader.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading