-
-
Save jbrains/dbadc637ea9e088d49220acce830a1be to your computer and use it in GitHub Desktop.
public static int factorsOfFiveIn(int n) { | |
int factorsOfFive = 0; | |
while (n > 1) { | |
if (n % 5 == 0) factorsOfFive++; | |
n /= 5; | |
} | |
return factorsOfFive; | |
} |
Found that it seems you can use iterate(...) :
public static long factorsOfFiveIn(int n) {
IntPredicate while_n_modulo_five_is_zero = x-> x % 5 == 0;
IntUnaryOperator divide_n_with_five = x -> x/5;
return IntStream.iterate(n, while_n_modulo_five_is_zero , divide_n_with_five).count();
}
or more compact, but less readable:
public static long factorsOfFiveIn(int n) {
return IntStream.iterate(n, x-> x % 5 == 0, x -> x/5).count();
}
@EffectiveLabs Not quite. 25 has the factor 5 twice, so 25! adds 2 zeroes to the end compared to 24!.
I tried to write what you describe with Vavr (Java FP library) and somehow I got it wrong, which led me in the direction I went in the end. I had tried to map n
to n%5==0
and then count all the true
values. I still don't know how I got that wrong.
@jonsweimarck Thank you for this! I really like the version with the anonymous functions. I didn't know about iterate()
, and Vavr's version also has it. This gives me a direction in which to refactor.
Using Vavr's implementations: divide n by 5 as long as n is a multiple of 5, then count the number of times you successfully divided n by 5.
public static int factorsOfFiveIn(int n) {
return Stream.iterate(n, divideBy(5))
.map(isAMultipleOf(5))
.takeWhile(isTrue())
.length();
}
As a post script, I found an alternative implementation of the larger exercise, which makes factorsOfFiveIn()
obsolete. :) I'll publish the whole thing somewhere quite soon.
Your short recursive version is very expressive imho. It is not tail recusive but that doesn't matter in java as java can't optimize tail recursions anyway...
So for very high n, you will get an Overflow Exception.
This seems to be one of the many things that makes it hard to do functional stuff in plain java.