Introduction
In this lab, you will learn how to check if a given number is a Fibonacci number in Java. We will explore three different approaches to achieve this.
First, you will learn how to generate the Fibonacci sequence up to a specified number of terms. Then, you will implement a method to check if a given number exists within the generated sequence. Finally, we will optimize the checking process by utilizing a mathematical formula that can efficiently determine if a number is a Fibonacci number without generating the entire sequence.
Generate Fibonacci Sequence
In this step, we will write a Java program to generate the Fibonacci sequence up to a certain number of terms. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.
We will create a new Java file and write the code to generate this sequence.
Open the WebIDE if it's not already open. You should be in the
~/projectdirectory by default. If not, open the Terminal at the bottom and type:cd ~/projectCreate a new file named
Fibonacci.javain the~/projectdirectory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typingFibonacci.java.Open the
Fibonacci.javafile in the editor and copy and paste the following Java code:import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of terms for Fibonacci sequence: "); int n = scanner.nextInt(); if (n <= 0) { System.out.println("Please enter a positive integer."); } else if (n == 1) { System.out.println("Fibonacci sequence up to 1 term:"); System.out.println("0"); } else { System.out.println("Fibonacci sequence up to " + n + " terms:"); int firstTerm = 0; int secondTerm = 1; System.out.print(firstTerm + ", " + secondTerm); for (int i = 3; i <= n; ++i) { int nextTerm = firstTerm + secondTerm; System.out.print(", " + nextTerm); firstTerm = secondTerm; secondTerm = nextTerm; } System.out.println(); // Print a newline at the end } scanner.close(); } }Let's quickly understand the key parts of this code:
import java.util.Scanner;: Imports theScannerclass to read user input.public class Fibonacci: Declares the main class namedFibonacci.public static void main(String[] args): The main method where the program execution begins.Scanner scanner = new Scanner(System.in);: Creates aScannerobject to read input from the console.System.out.print("Enter the number of terms... ");: Prompts the user to enter the number of terms.int n = scanner.nextInt();: Reads the integer input from the user and stores it in the variablen.- The
if-else if-elseblock handles different cases for the number of terms (n). int firstTerm = 0; int secondTerm = 1;: Initializes the first two terms of the sequence.System.out.print(firstTerm + ", " + secondTerm);: Prints the first two terms.- The
forloop calculates and prints the subsequent terms. int nextTerm = firstTerm + secondTerm;: Calculates the next term by summing the previous two.firstTerm = secondTerm; secondTerm = nextTerm;: UpdatesfirstTermandsecondTermfor the next iteration.scanner.close();: Closes theScannerobject.
Save the
Fibonacci.javafile (Ctrl+S or Cmd+S).Now, compile the Java program using the
javaccommand in the Terminal:javac Fibonacci.javaIf there are no errors, this command will create a
Fibonacci.classfile in the~/projectdirectory.Finally, run the compiled program using the
javacommand:java FibonacciThe program will prompt you to enter the number of terms. Enter a number (e.g., 10) and press Enter to see the Fibonacci sequence.
Enter the number of terms for Fibonacci sequence: 10 Fibonacci sequence up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
You have successfully written, compiled, and run a Java program to generate the Fibonacci sequence!
Check if Number Exists in Sequence
In this step, we will modify our Java program to check if a given number exists within the generated Fibonacci sequence. This involves adding logic to compare the user's input number with the terms of the sequence as they are generated.
Open the
Fibonacci.javafile in the WebIDE editor.Modify the
mainmethod to include the logic for checking if a number exists in the sequence. Replace the existingmainmethod with the following code:import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of terms for Fibonacci sequence: "); int n = scanner.nextInt(); if (n <= 0) { System.out.println("Please enter a positive integer for the number of terms."); scanner.close(); return; // Exit the program } System.out.print("Enter the number to check if it exists in the sequence: "); int checkNum = scanner.nextInt(); System.out.println("Fibonacci sequence up to " + n + " terms:"); int firstTerm = 0; int secondTerm = 1; boolean found = false; // Check the first two terms if (checkNum == firstTerm) { found = true; } System.out.print(firstTerm); if (n > 1) { if (checkNum == secondTerm) { found = true; } System.out.print(", " + secondTerm); } // Generate and check subsequent terms for (int i = 3; i <= n; ++i) { int nextTerm = firstTerm + secondTerm; if (checkNum == nextTerm) { found = true; } System.out.print(", " + nextTerm); firstTerm = secondTerm; secondTerm = nextTerm; } System.out.println(); // Print a newline at the end if (found) { System.out.println(checkNum + " exists in the Fibonacci sequence."); } else { System.out.println(checkNum + " does not exist in the Fibonacci sequence."); } scanner.close(); } }Here's a breakdown of the changes:
- We added a prompt to ask the user for the number they want to check (
System.out.print("Enter the number to check...")). - We read this number into a new variable
checkNum(int checkNum = scanner.nextInt();). - A boolean variable
foundis initialized tofalse. This variable will track if the number is found in the sequence. - We check if
checkNumis equal to thefirstTermorsecondTermbefore the loop. - Inside the
forloop, after calculatingnextTerm, we check ifcheckNumis equal tonextTerm. If it is, we setfoundtotrue. - After the loop finishes, we use an
if-elsestatement to print whether the number was found based on the value of thefoundvariable.
- We added a prompt to ask the user for the number they want to check (
Save the
Fibonacci.javafile.Compile the modified program in the Terminal:
javac Fibonacci.javaRun the compiled program:
java FibonacciThe program will now ask for the number of terms and then the number to check.
Example 1 (Number exists):
Enter the number of terms for Fibonacci sequence: 10 Enter the number to check if it exists in the sequence: 8 Fibonacci sequence up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 8 exists in the Fibonacci sequence.Example 2 (Number does not exist):
Enter the number of terms for Fibonacci sequence: 10 Enter the number to check if it exists in the sequence: 10 Fibonacci sequence up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 10 does not exist in the Fibonacci sequence.
You have successfully modified your program to check if a number is part of the generated Fibonacci sequence.
Optimize with Mathematical Formula
In the previous steps, we generated the Fibonacci sequence iteratively and checked if a number exists by comparing it with each term. For very large numbers, generating the entire sequence can be inefficient. In this step, we will explore a mathematical property of Fibonacci numbers that allows us to check if a number is a Fibonacci number without generating the sequence.
A positive integer x is a Fibonacci number if and only if either 5*x^2 + 4 or 5*x^2 - 4 is a perfect square. A perfect square is an integer that is the square of an integer (e.g., 4 is a perfect square because it's 2*2).
We will create a new Java program that uses this formula to check if a number is a Fibonacci number.
Create a new file named
CheckFibonacci.javain the~/projectdirectory.Open
CheckFibonacci.javaand copy and paste the following Java code:import java.util.Scanner; public class CheckFibonacci { // Function to check if a number is a perfect square public static boolean isPerfectSquare(int n) { if (n < 0) { return false; } int sqrt = (int) Math.sqrt(n); return (sqrt * sqrt == n); } // Function to check if a number is a Fibonacci number public static boolean isFibonacci(int n) { // n is Fibonacci if 5*n^2 + 4 or 5*n^2 - 4 is a perfect square return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number to check if it is a Fibonacci number: "); int num = scanner.nextInt(); if (isFibonacci(num)) { System.out.println(num + " is a Fibonacci number."); } else { System.out.println(num + " is not a Fibonacci number."); } scanner.close(); } }Let's look at the new parts of this code:
public static boolean isPerfectSquare(int n): This is a helper function that takes an integernand returnstrueifnis a perfect square, andfalseotherwise. It calculates the integer square root and checks if squaring it gives back the original number.public static boolean isFibonacci(int n): This function implements the mathematical formula. It calculates5*n*n + 4and5*n*n - 4and uses theisPerfectSquarefunction to check if either result is a perfect square. The||operator means "or".- The
mainmethod now prompts the user for a number, calls theisFibonaccifunction, and prints the result.
Save the
CheckFibonacci.javafile.Compile the new program in the Terminal:
javac CheckFibonacci.javaRun the compiled program:
java CheckFibonacciThe program will ask you to enter a number. Enter a number (e.g., 13) and press Enter.
Example 1 (Fibonacci number):
Enter a number to check if it is a Fibonacci number: 13 13 is a Fibonacci number.Example 2 (Not a Fibonacci number):
Enter a number to check if it is a Fibonacci number: 10 10 is not a Fibonacci number.
This method is much more efficient for checking if a single large number is a Fibonacci number compared to generating the sequence up to that number.
Summary
In this lab, we learned how to check if a number is a Fibonacci number in Java. We started by generating the Fibonacci sequence up to a certain number of terms using a simple iterative approach. This involved understanding the definition of the Fibonacci sequence and implementing the logic to calculate and print the terms.
Next, we explored how to check if a given number exists within the generated Fibonacci sequence. Finally, we learned about an optimized approach using a mathematical formula to efficiently determine if a number is a Fibonacci number without explicitly generating the entire sequence. This involved understanding the properties of Fibonacci numbers and applying the formula to perform the check.



