In this section, you will learn how to find the prime numbers which are generated in the fibonacci series. To compute this, we have created two methods generateSeries() of ArrayList type and isPrime() of boolean type. After that we have stored the fibonacci number series of 10 numbers in the list. The Iterator class iterates the ArrayList and check whether number is prime or not? If it is prime Number, the number will get displayed.
Here is the code:
import java.util.*;
public class PrimeAndFibonacci {
int no;
private ArrayList list = new ArrayList();
ArrayList generateSeries(int num) {
int f1, f2 = 0, f3 = 1;
for (int i = 1; i <= num; i++) {
list.add(f3);
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
return list;
}
static boolean isPrime(int number) {
boolean isPrime = false;
int i = (int) Math.ceil(Math.sqrt(number));
while (i > 1) {
if ((number != i) && (number % i == 0)) {
isPrime = false;
break;
} else if (!isPrime)
isPrime = true;
--i;
}
return isPrime;
}
public static void main(String[] args) {
ArrayList palindromes = new ArrayList();
PrimeAndFibonacci pf = new PrimeAndFibonacci();
palindromes = pf.generateSeries(10);
Iterator iter = palindromes.iterator();
while (iter.hasNext()) {
int reqNo = iter.next();
if (isPrime(reqNo))
System.out.println(reqNo);
}
}
}
Output 2 3 5 13
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.