Reputation: 55
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);
}
}
}
Upvotes: 2
Views: 3185
Reputation: 540
If you want to do it using java stream, you can do it like this.
public boolean isArmstrongNumber(String number) {
int exponent = number.length();
if (Integer.parseInt(number) == number.chars()
.map(n -> n - '0')
.map(n ->(int) Math.pow(Integer.parseInt("" + n),exponent))
.sum())
return true;
else return false;
}
Upvotes: 0
Reputation: 423
Maybe im mistaken (its 1AM here..), but as far as i can tell your implementation is actually not a recursion at all. With
while (temp != 0){ remainder = temp % 10; sum += Math.pow(remainder, digits); temp = temp / 10; }
you do the whole calculation iteratively, until tmp is 0. Therefore in the next line
return sum + arm(temp);
arm(temp) will always return 0!
I hacked together a quick recursion of my own, which works digit by digit, starting from the last. The function overload is necessary because every recursive call needs the total length of the original number.
public static long arm(long n){
return arm(n, Integer.toString(n).length());
}
public static long arm(long n, int num_digits){
if(n==0) //recursion finished
return;
// n%10 gives last digit
return java.lang.Math.pow(n%10,num_digits) + arm(n/10, num_digits);
}
I hope you like it ;-)
Upvotes: 4