Algorithm Analysis
Let's denote by the number of ways in which a 2 × rectangle can be covered with 2 × 1 domino pieces. Obviously,
, one vertical piece;
, two vertical or two horizontal pieces.
Consider the algorithm for calculating . One can place one piece vertically and then cover the rectangle of length in ways, or place two pieces horizontally and then cover the rectangle of length in ways. Thus, .
Thus, is a Fibonacci number.
Algorithm Implementation
Since , one should use long arithmetic or the Java programming language.
import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { Scanner con = new Scanner(System.in); int n = con.nextInt(); BigInteger a = new BigInteger("1"), b = a; for(int i = 0; i < n; i++) { BigInteger temp = a.add(b); a = b; b = temp; } System.out.println(a); con.close(); } }