Java Exp No 9-Pages
Java Exp No 9-Pages
DATE –
Aim:
Background Theory:
1. The sum of the first N Fibonacci numbers (using the fibo thread).
2. The sum of the first N prime numbers (using the prime thread).
Concepts Used:
• Threads in Java: The program creates two separate threads (fibo and prime) to
perform calculations concurrently.
• Fibonacci Sequence: Each number is the sum of the two preceding numbers. The
sum is calculated iteratively.
• Prime Numbers: A number is prime if it has only two divisors: 1 and itself. The
program finds and sums the first N prime numbers.
• Concurrency: Both calculations run in parallel, improving efficiency.
Algorithm:
Step 1: Take Input
2. Create a fibo thread to compute the sum of the first N Fibonacci numbers.
3. Create a prime thread to compute the sum of the first N prime numbers.
4. Start both threads using start(), allowing them to run concurrently.
package workout;
import java.util.*;
fibo(int n){
this.n=n;
this.first=0;
this.second=1;
this.res=1;
}
public void run() {
try {
Thread.sleep(1000);
for(int i=2;i<n;i++) {
int temp=first+second;
first=second;
second=temp;
res+=temp;
}
System.out.println("The sum of fibonacci series is "+ res); }
catch(Exception e) { } } }
prime(int n) {
this.n = n;
res = 0;
count = 0;
num = 2; // Start checking from 2
primesFound = 0;
}
}
Output:
Result:
Thus, the program correctly computes the sum of the first N prime numbers and the
sum of the first N Fibonacci numbers concurrently,
EXP NO – 9(c) Implementation of multi threading
DATE –
Aim:
To implement a multi-threaded program in C++ that efficiently finds and displays all
prime numbers within a given range [n, m] by dividing the workload between multiple
threads, optimizing execution time.
Background Theory:
This program demonstrates multi-threading in C++ by dividing a given range [n, m] into
multiple subranges, where each thread processes a subrange to find prime numbers.
Concepts Used:
Algorithm:
#include <iostream>
#include <thread>
int main() {
cin >> n >> m;
if (n > m) {
cout << "Invalid range" << endl;
return 0;
}
t1.join();
t2.join();
return 0;
}
Output:
Result:
Thus, the program correctly finds and displays all prime numbers within the given range
using optimized multi-threading.