Lập trình Java - Viết chương trình liệt kê các số Fibonacci nhỏ hơn n là số nguyên tố

Đề bài: Viết chương trình liệt kê các số Fibonacci nhỏ hơn n là số nguyên tố trong Java. N là số nguyên dương được nhập từ bàn phím.

Mã nguồn chương trình:


import java.util.Scanner;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author ADMIN
 */
public class Bai10 {

    /**
     * @param args the command line arguments
     */
    public static int fibonacci(int n) {
        if (n < 0) {
            return -1;
        } else if (n == 0 || n == 1) {
            return n;
        } else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }
    }
     
    
    public static boolean isPrimeNumber(int n) {
        // so nguyen n < 2 khong phai la so nguyen to
        if (n < 2) {
            return false;
        }
        // check so nguyen to khi n >= 2
        int squareRoot = (int) Math.sqrt(n);
        for (int i = 2; i <= squareRoot; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner input= new Scanner(System.in);
         System.out.print("Nhập số tự nhiên n = ");
        int n = input.nextInt();
        System.out.printf("Các số fibonacci nhỏ hơn %d và là số nguyên tố: ", n);
        int i = 0;
        while (fibonacci(i) < 100) {
            int fi = fibonacci(i);
            if (isPrimeNumber(fi)) {
                System.out.print(fi + " ");
            }
            i++;
        }
    }
    
}

Kết quả:

Nhập số tự nhiên n = 100
Các số fibonacci nhỏ hơn 100 và là số nguyên tố: 2 3 5 13 89