Answer to Question #257507 in Java | JSP | JSF for Nikhil Sahoo

Question #257507

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.


1
Expert's answer
2021-10-27T18:51:28-0400
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:

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS