You are on page 1of 5

GENERATING PRIME NUMBERS AND FIBONACCI SERIES

AIM:
To write a java program to generate prime numbers and fibonacci series.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Import the necessary packages.
STEP 3: Create tow threads MyThread1 and MyThread2.
STEP 4: In MyThread1 create instances for piped reader and piped writer.
STEP 5: Create a constructor and assign values to them.
STEP 6: In mythread2 create instances for pipedreader and piped writer.
STEP 7: Create a constructor and assign values to them.
STEP 8: Declare a class Multithreaded programming and create two list using ArrayList
STEP 9: Display the output.
STEP 10: Stop the program.

PROGRAM:
import java.io.*;
import java.util.*;
public class Prime extends Thread
{
private PipedReader pr;
private PipedWriter pw;
Prime(PipedReader pr, PipedWriter pw)
{
this.pr = pr;
this.pw = pw;
}
public void run()
{
try
{
int i;
for (i=1;i<10;i++)
{
int j;
for (j=2; j<i; j++)
{
int n = i%j;
if (n==0)
{
break;
}
}
if(i == j)
{
pw.write(i+"\n");
}
}
pw.close();
}
catch (IOException e)
{
}
}
}
class MyThread2 extends Thread
{
private PipedReader pr;
private PipedWriter pw;
MyThread2(PipedReader pr, PipedWriter pw)
{
this.pr = pr;
this.pw = pw;
}
public void run()
{
try
{
int f1, f2 = 1, f3 = 1;
for (int i = 1; i <10; i++)
{
pw.write(f3+"\n");
f1 = f2;
f2 = f3;
f3 = f1 + f2;
}
pw.close();
}
catch (IOException e)
{
}
}
}
class MultithreadedProgram
{
public static void main(String[] args) throws Exception
{
ArrayList list1=new ArrayList();
ArrayList list2=new ArrayList();
PipedWriter pw1 = new PipedWriter();
PipedReader pr1 = new PipedReader(pw1);
Prime mt1 = new Prime(pr1, pw1);
System.out.println("Prime Numbers: ");
mt1.start();
int item1;
while ((item1 = pr1.read()) != -1)
{
char ch1=((char) item1);
System.out.print(Character.toString(ch1));
list1.add(Character.toString(ch1));
}
pr1.close();
PipedWriter pw2 = new PipedWriter();
PipedReader pr2 = new PipedReader(pw2);
MyThread2 mt2 = new MyThread2(pr2, pw2);
System.out.println("Fibonacci Numbers: ");
mt2.start();
int item2;
while ((item2 = pr2.read()) != -1)
{
char ch2=((char) item2);
System.out.print(Character.toString(ch2));
list2.add(Character.toString(ch2));
}
pr2.close();
System.out.println("Elements common to both lists are:");
list1.retainAll(list2);
for(int i=0;i<list1.size();i++)
{
System.out.print(list1.get(i));
}
}
}










OUTPUT:
Prime Numbers:
2
3
5
7
Fibonacci Numbers:
1
2
3
5
8
13
21
34
55
Elements common to both lists are:
2
3
5











RESULT:
Thus the program for generating prime numbers and fibonacci series is done and the output is verified
successfully.

You might also like