diff --git a/src/Fibonacci.java b/src/Fibonacci.java new file mode 100644 index 0000000000000000000000000000000000000000..e5dcf2720d9436bfae7000e04ca57fbebc23b607 --- /dev/null +++ b/src/Fibonacci.java @@ -0,0 +1,48 @@ +import java.io.*; +import java.util.*; +import javax.servlet.*; +import javax.servlet.http.*; +import javax.servlet.annotation.WebServlet; + +@WebServlet("/Fibonacci") +public class Fibonacci extends HttpServlet +{ + public void service( HttpServletRequest req, HttpServletResponse res ) + throws ServletException, IOException + { + res.setContentType("text/html;charset=UTF-8"); + PrintWriter out = res.getWriter(); + out.println( "<head><title>Fibonacci</title>" ); + out.println( "<META content=\"charset=UTF-8\"></head><body>" ); + + out.println( "<center>Fibonacci</center><p>"); + + FibonacciSequence seq = new FibonacciSequence(); + + for (int x = 0; x <= 30; ++x) { + int y = seq.get(x); + out.println(String.format("<span><b>f(%d)</b> = %d</span><br/>", x, y)); + } + + out.println( "</p>"); + } + + private class FibonacciSequence { + private Map<Integer, Integer> CACHE = new HashMap<Integer, Integer>(); + + public int get(int n) { + if (n <= 1) return n; + + if (CACHE.containsKey(n)) { + return CACHE.get(n); + } + + int a = get(n - 1); + int b = get(n - 2); + int x = a + b; + + CACHE.put(n, x); + return x; + } + } +} \ No newline at end of file