Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.claude_martin.playground;
- import java.util.Map;
- import java.util.TreeMap;
- import java.util.stream.LongStream;
- // see https://oeis.org/A001923
- public final class SomeClass {
- /**
- * As solved by Muhammad.
- */
- static long f0(long n) {
- long sum = 0;
- for (int j = 1; j <= n; j++) {
- sum += Math.pow(j, j);
- }
- return sum;
- }
- /**
- * Recursive.
- */
- static long f1(long n) {
- if (n == 0L)
- return 0L;
- return power(n) + f1(n - 1);
- }
- /** Stream API. */
- static long f2(int n) {
- return LongStream.rangeClosed(1, n).map(SomeClass::power).sum();
- }
- /** Naive. */
- static long f3(int n) {
- long result = 0;
- for (int i = 1; i <= n; i++)
- result += power(i);
- return result;
- }
- /** Extra naive. */
- static long f4(int n) {
- if (n == 0)
- return 0;
- long result = 1;
- for (int i = 2; i <= n; i++) {
- long pow = 1;
- for (int j = 0; j < i; j++)
- pow *= i;
- result += pow;
- }
- return result;
- }
- static final Map<Integer, Long> cache = new TreeMap<>();
- /** Cached, using {@link #f1(long)}. */
- static long cached(int n) {
- return cache.computeIfAbsent(n, SomeClass::f1);
- }
- /** n<sup>n</sup>. */
- static long power(final long number) {
- long res = 1;
- long sq = number;
- long power = number;
- while (power > 0) {
- if (power % 2 == 1) {
- res *= sq;
- }
- sq = sq * sq;
- power /= 2;
- }
- return res;
- }
- public static void main(String[] args) {
- for (int i = 0; i < 17; i++) {
- long f0 = f0(i);
- long f1 = f1(i);
- long f2 = f2(i);
- long f3 = f3(i);
- long f4 = f4(i);
- long cached = cached(i);
- assert (f0 == f1) : f0 + " != " + f1;
- assert (f0 == f2) : f1 + " != " + f2;
- assert (f0 == f3) : f1 + " != " + f3;
- assert (f0 == f4) : f1 + " != " + f4;
- assert (f0 == cached) : f1 + " != " + cached;
- System.out.print("A001923(");
- System.out.print(i);
- System.out.print(") = ");
- System.out.print(f1);
- System.out.println();
- }
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement