Write a program in Java to store first 20 Fibonacci numbers in an array then display only those Fibonacci which are prime. And also display how many such numbers found.
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n1,n2,terms=20,n3;
double series[]=new double[terms];
System.out.println("Enter the first and second terms of the array:");
Scanner sc=new Scanner(System.in);
System.out.println("First term of the fibonacciSeries:"+(n1=sc.nextInt()));
System.out.println("Sirst term of the fibonacciSeries:"+(n2=sc.nextInt()));
for(int i=0;i<terms;i++){
n3=n1+n2;
series[i]=n3;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
System.out.println("\n The required fibonacci series is:");
for(int i=0;i<terms;i++){
System.out.print(" "+(int)series[i]+" ");
}
System.out.println("\n The prime numbers are listed below:");
for(int i=0; i<series.length; i++) {
int j=2;
int p=1;
while (j < series[i]) {
if (series[i] % j == 0) {
p = 0;
break;
}
j++;
}
if (p == 1) {
System.out.print(" "+(int)series[i]);
}
}
}
}
Output:
Comments
Leave a comment