Reputation: 145
Ive created this code that finds the number of animals given the number of heads and legs
public class howmanyAnimals {
public static void main(String[] args) {
int Heads = 100;
int legs = 300;
int animals = animalHeads(Heads, legs);
System.out.println("Number of cows: " + animals);
System.out.println("Number of chickens: "+ (Heads - animals));
}
static int animalHeads(int heads, int legs) {
int count = 0;
count = (legs) - 2 * (heads);
count = count / 2;
return count;
}
}
output:
Number of cows: 50
Number of chickens: 50
This works fine however the method animalHeads needs to be Recurive
I attempted this method
static int animalHeads(int heads, int legs) {
int count = 0;
count = (legs) - 2 * (heads);
count = count / 2;
if (count % 2 == 0) {
return 0;
} else if (count % 2 != 0) {
return count = animalHeads(100, 300);
}
return count;
}
}
but im a bit rusty with recursion.
Upvotes: 2
Views: 306
Reputation: 393846
Well, animalHeads
actually calculates the number of cows.
Since a cow has 1 head and 4 legs, the recursive step should be:
animalHeads(heads, legs) = 1 + aminalHeads(heads - 1, legs - 4);
However, since the heads and legs count include chickens, which have 1 head and 2 legs, the recursion should end when all the remaining heads and legs belong to chickens, which happens when the remaining number of legs is twice the remaining number of heads.
static int animalHeads(int heads, int legs)
{
if (heads * 2 == legs) { // only chickens are left
return 0;
}
return 1 + animalHeads(heads - 1, legs - 4);
}
Upvotes: 4