Nth Fibonacci

Assignment

Write a class called Fibonacci with a method public static long fib(int n) that returns the nth Fibonacci number, where fib(1) == 1 and fib(2) == 1.

The student submits this as Fibonacci.java.

Sample Solution

public class Fibonacci {
    public static long fib(int n) {
        long cur = 1, next = 1;
        for (int i = 1; i < n; i++) {
            long tmp = cur + next;
            cur = next;
            next = tmp;
        }
        return cur;
    }
}

Example Grader

import static org.junit.Assert.assertEquals;

import org.junit.Test;

// Uploaded as the assignment's grader file (stored as `Grader.java`). Each test
// is worth 1 point unless annotated with @Weight(n). The score is the sum of the
// passing tests' weights, so set "Points possible" to the total (10 here).
public class Grader {

    @Test
    @Weight(1)
    public void fib1() {
        assertEquals(1L, Fibonacci.fib(1));
    }

    @Test
    @Weight(1)
    public void fib2() {
        assertEquals(1L, Fibonacci.fib(2));
    }

    // No @Weight, so this test is worth 1 point (the default).
    @Test
    public void fib10() {
        assertEquals(55L, Fibonacci.fib(10));
    }

    @Test
    @Weight(2)
    public void fib20() {
        assertEquals(6765L, Fibonacci.fib(20));
    }

    // The hardest case is worth the most.
    @Test
    @Weight(5)
    public void fib50() {
        assertEquals(12586269025L, Fibonacci.fib(50));
    }
}

This grader uses @Weight(n) to weight the harder cases more heavily: the weights are 1 + 1 + 1 + 2 + 5 = 10, so set the assignment’s “Points possible” to 10. Note fib10 has no @Weight and so is worth 1 point (the default) - you can mix weighted and unweighted tests freely. A submission that passes everything except fib50 scores 5 out of 10.