Is there a more elegant way to write this recursively? Armstrong Numbers
PS: been out of school for 15 years this is not homework, just some code I am trying to convert from iterative to recursively.
import java.util.Scanner;
public class RecArmstrong {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
//Error checking
while(number < 0 || number > 100000){
System.out.print("Enter a number: ");
number = keyboard.nextInt();
}
if(arm(number) == number)
System.out.println(number + " is an armstrong number");
else
System.out.println(number + " is not an armstrong number.");
}
public static long arm(long n){
long temp, sum, digits = 0;
long remainder;
temp = n;
sum = 0;
if (temp == 0)
return 0; //base case
else{
while (temp != 0){
digits++; //number of digits for exponent
temp = temp / 10;
}
temp = n; //set temp back to original number
while (temp != 0){
remainder = temp % 10;
sum += Math.pow(remainder, digits);
temp = temp / 10;
}
return sum + arm(temp);
}
}
}