Created
August 10, 2021 19:31
-
-
Save shelajev/fd16adf17e17892daac125bb816f1062 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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