The Cat In The Hat has cat A under his hat, cat A has cat B under his
hat and so on until Z.The Cat In The Hat is 2,000,000 cat units tall.
Each cat is 2.5 times bigger than the cat underneath their hat.
Find the total height of the cats if they are standing on top of one
another.Counting starts from the Cat In The Hat
n = the number of cats
fix to 3 decimal places.
I tried to solve this by
function height(n) {
const a = 2.5;
const repetition = 2000000;
let result = 0;
for (let i = 0; i < repetition; i++) {
result += n * a;
}
return result.toFixed(3);
}
I’m assuming its not working because the numbers are really big and it may be interfering with the result. At 1st I did expect this to work but it did not.
This is a problem on Code Wars that I’m having a hard time solving.
2
Answers
My understanding that the problem you’re facing stems from the way you’re calculating the height. The loop in your code is repeating the addition of n * a for repetition number of times. However, this approach doesn’t correctly account for the fact that each subsequent cat is 2.5 times bigger than the previous one.
To solve this problem, you can use a recursive function that calculates the height by multiplying the height of the previous cat by 2.5 and adding it to the height of the current cat.
Here’s an example implementation
In this code, the
height
function recursively calculates the height of each cat by multiplying the height of the previous cat by 2.5 and adding it to the current cat’s height. The base caseif (n === 0)
stops the recursion when it reaches the Cat in the Hat.Using this approach, the total height of the cats, starting from the Cat in the Hat and going through 26 cats (A to Z), is approximately 11,718,750.000 units when rounded to 3 decimal places.
Hope this makes sense.
I think you really have to read the question closely here,.
The original cat is 2_000_000 units high, so we start at that.
Each cat under each cat hat is 2.5 times smaller,.
Each cat is 2.5 times bigger than the cat underneath their hat.
note it says cat underneath, not on top. So you divide by 2.5, not multiply.And of course there are 27 cats, as their is a-z, plus the original cat in the hat.
So the code ->