I guess you only posted this to get advice on performance, but I will nonetheless give you a short code review because your code is very sloppy (not the actual logic, but cleanliness / readability).
The whole block of code
while (num >= 1) should be made a function called maybe
solve instead of just being some code within the main method.
Java naming convention would use instead
I would personally have kept the natural index as the key in
countarray[num] is the count for
num instead of having to call
countarray[num - 1] everywhere. Of course,
countarray would be of size
num + 1 and
countarray is meaningless.
Try to label all
final member variables as such. So here
final. Most new languages have that all variables are immutable (aka final) by default, unless otherwise specified. It's easier to reason about code when you who most things can't change.
Java has the syntax
5_000_000. I actually had to count the zeros because I was not sure if it was 500,000 or 5,000,000.
You should have defined something like
private static final int CACHE_SIZE = 5_000_000 and use that throughout your code. Now you have
5000000 hard coded everywhere which makes it awkward if you want to modify it. Also maybe in one place you could mistakenly write
I don't like too much that
count is static (of course
countarray should be static). But I guess you had no choice since you used a functional style instead of an object-oriented style so you only have static methods. But you can look what others did submitting this very same problem for review on this site (see "Related" on the right of this page). Functional style is probably better for this task, but it's not quite the Java way. That would have been more appropriate for example in Kotlin.
On a different note, related to some comments above, I did some search and it does seem that now the JVM can sometimes inline some recursive. I was glad to see that since it can make big performance improvements. Nevertheless, you should keep in mind that it probably won't inline all recursive functions and you might sometimes performance penalty using recursion.
Also, did you figure out how to get better performance? Many people posted reviews for the exact same problem (see "Related" on the right of this page) and they have pretty much the same solution as you and no one seemed to have performance problems.