Home Tutorial Java Core Prime And Fibonacci Number Finder

 
 

Share on Google+Share on Google+
Prime And Fibonacci Number Finder
Posted on: November 10, 2009 at 12:00 AM
Advertisement
In this section, you will learn how to find the prime numbers which are generated in the fibonacci series.

Prime And Fibonacci Number Finder

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
Advertisement

Related Tags for Prime And Fibonacci Number Finder :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 10, 2009

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com