Skip to content

Instantly share code, notes, and snippets.

@shelajev
Created August 10, 2021 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shelajev/fd16adf17e17892daac125bb816f1062 to your computer and use it in GitHub Desktop.
Save shelajev/fd16adf17e17892daac125bb816f1062 to your computer and use it in GitHub Desktop.
package com.example;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import java.util.HashMap;
import java.util.Map;
@Controller("/")
public class FibonacciController {
private static final StringBuilder LOG = new StringBuilder();
private static final Map<Integer, Long> CACHE = new HashMap();
@Get(uri = "/nthFibonacci/{nth}", produces = MediaType.TEXT_PLAIN)
public String nthFibonacci(Integer nth) {
long[] counter = new long[] {0};
long start = System.currentTimeMillis();
LOG.append("Fibonacci number #").append(nth).append(" is ");
LOG.append(computeNthFibonacci(nth, counter));
LOG.append(" (computed in ").append(System.currentTimeMillis() - start).append(" ms, ").append(counter[0]).append(" steps)\n");
return LOG.toString();
}
private static long computeNthFibonacci(int nth, long[] counter) {
counter[0]++;
if (nth == 0 || nth == 1) return nth;
Long result = CACHE.get(nth);
if (result == null) {
result = computeNthFibonacci(nth - 1, counter) + computeNthFibonacci(nth - 2, counter);
CACHE.put(nth, result);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment