diff --git a/exercises/practice/raindrops/.approaches/introduction.md b/exercises/practice/raindrops/.approaches/introduction.md index 48b7d6b07..278785921 100644 --- a/exercises/practice/raindrops/.approaches/introduction.md +++ b/exercises/practice/raindrops/.approaches/introduction.md @@ -54,6 +54,32 @@ class RaindropConverter { For more information, check the [`Map` approach][approach-map]. +## Approach: `Modular Arithmetic` + +```java +import java.math.BigInteger; +import static java.math.BigInteger.valueOf; + +class RaindropConverter { + + String convert (int n) { + return switch ( valueOf(n).modPow( valueOf(12), valueOf(105) ).intValue() ) { + case 36 -> "Pling"; + case 85 -> "Plang"; + case 91 -> "Plong"; + case 15 -> "PlingPlang"; + case 21 -> "PlingPlong"; + case 70 -> "PlangPlong"; + case 0 -> "PlingPlangPlong"; + default -> String.valueOf(n); // 1 + }; + } + +} +``` + +Fizz-Buzz is a related problem to raindrops. Both can be solved in the general case using Euler's totient theorem as long as all the sounds/factors are co-prime. For more information, check this article on a [`modular arithmetic` approach][approach-modular]. + ## Which approach to use? Benchmarking with the [Java Microbenchmark Harness][jmh] is currently outside the scope of this document, @@ -64,4 +90,5 @@ and no other code would need to be added. [remainder-operator]: https://www.geeksforgeeks.org/modulo-or-remainder-operator-in-java/ [approach-if-statements]: https://exercism.org/tracks/java/exercises/raindrops/approaches/if-statements [approach-map]: https://exercism.org/tracks/java/exercises/raindrops/approaches/map +[approach-modular]: https://philcrissman.net/posts/eulers-fizzbuzz/ [jmh]: https://github.com/openjdk/jmh