ต่อไปนี้เป็นโปรแกรม Java เพื่อตรวจสอบว่าตัวเลขที่กำหนดคือ Fibonacci หรือไม่ −
ตัวอย่าง
public class Demo{
static boolean perfect_square_check(int val){
int s = (int) Math.sqrt(val);
return (s*s == val);
}
static boolean fibonacci_num_check(int n){
return perfect_square_check(5*n*n + 4) || perfect_square_check(5*n*n - 4);
}
public static void main(String[] args){
for (int i = 6; i <= 17; i++)
System.out.println(fibonacci_num_check(i) ? i + " is a Fibonacci number" :
i + " is a not Fibonacci number");
}
} ผลลัพธ์
6 is a not Fibonacci number 7 is a not Fibonacci number 8 is a Fibonacci number 9 is a not Fibonacci number 10 is a not Fibonacci number 11 is a not Fibonacci number 12 is a not Fibonacci number 13 is a Fibonacci number 14 is a not Fibonacci number 15 is a not Fibonacci number 16 is a not Fibonacci number 17 is a not Fibonacci number
คลาสชื่อ Demo กำหนดฟังก์ชันบูลีนแบบคงที่ซึ่งรับค่าจำนวนเต็มเป็นพารามิเตอร์ โดยจะตรวจสอบรากที่สองของค่าและกำหนดให้กับค่าอื่น หากผลคูณของสแควร์รูทคูณด้วยสแควร์รูทเท่ากับค่าที่ส่งไป จะถูกส่งกลับ
ถัดไป มีการกำหนดฟังก์ชันบูลีนสแตติกอื่นที่เรียกใช้ฟังก์ชันก่อนหน้า ในฟังก์ชันหลัก หมายเลขเริ่มต้นและหมายเลขลงท้ายจะถูกทำซ้ำ และข้อความที่เกี่ยวข้องจะถูกพิมพ์ตลอดจนตรวจสอบว่าทุกหมายเลขเป็นหมายเลข Fibonacci หรือไม่