0% found this document useful (0 votes)
7 views11 pages

Java Exp No 9-Pages

The document outlines the implementation of multi-threaded programs in Java and C++ to compute sums of prime and Fibonacci numbers concurrently, and to find prime numbers within a specified range, respectively. It details the algorithms, background theory, and coding for both programs, emphasizing the use of threads for efficient computation. The results confirm that both programs successfully achieve their aims through optimized multi-threading.

Uploaded by

sruthirajesh456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views11 pages

Java Exp No 9-Pages

The document outlines the implementation of multi-threaded programs in Java and C++ to compute sums of prime and Fibonacci numbers concurrently, and to find prime numbers within a specified range, respectively. It details the algorithms, background theory, and coding for both programs, emphasizing the use of threads for efficient computation. The results confirm that both programs successfully achieve their aims through optimized multi-threading.

Uploaded by

sruthirajesh456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

EXP NO – 9(b) Implementation of multi threading

DATE –

Aim:

Implement a multi-threaded program to compute the sum of the first N


prime numbers and the first N Fibonacci numbers concurrently. Each calculation
runs in a separate thread for efficiency. The program then outputs both sums after
computation.

Background Theory:

This program demonstrates multi-threading in Java by calculating:

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

1. Read an integer N from the user.

Step 2: Initialize and Start Threads

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.

Step 3: Fibonacci Calculation (fibo Thread)

5. Initialize first = 0, second = 1, and res = 1.


6. Iterate from 2 to N, updating Fibonacci values iteratively:
o Compute the next Fibonacci number: temp = first + second.
o Update first = second, second = temp, and add temp to res.
7. Print the sum of the Fibonacci series.

Step 4: Prime Number Calculation (prime Thread)

8. Initialize res = 0 and primesFound = 0.


9. Start checking numbers from 2, counting prime numbers found.
10. Use an optimized prime check:
o Count the number of divisors up to the square root of num.
o If exactly 2 divisors are found, it's a prime number.
11. Add the prime number to res and increment primesFound.
12. Repeat until N prime numbers are found.
13. Print the sum of the first N prime numbers.

Step 5: End Program

14. Both threads complete execution independently, printing their results


Coding:

package workout;

import java.util.*;

class fibo extends Thread{

public int n,first,second,res;

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) { } } }

class prime extends Thread {


int n, res, count, num, primesFound;

prime(int n) {
this.n = n;
res = 0;
count = 0;
num = 2; // Start checking from 2
primesFound = 0;
}

public void run() {


try {

while (primesFound < n) {


int divisorCount = 0;

for (int i = 1; i * i <= num; i++) { // Optimized prime check


if (num % i == 0) {
if (i * i == num) divisorCount++; // Perfect square case
else divisorCount += 2; // Two divisors: i and num/i
}
}
if (divisorCount == 2) { // Prime number found
res += num;
primesFound++;
}
num++;
}
System.out.println("The sum of the first " + n + " prime numbers is " + res);
} catch (Exception e) {
e.printStackTrace();
}
}
}

public class multi {

public static void main(String[] args) {


Scanner ob=new Scanner(System.in);
int n=ob.nextInt();
fibo thread1=new fibo(n);

prime thread2=new prime(n);


thread2.start();
thread1.start();

}
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:

• Threads in C++ (std::thread): Each thread handles a portion of the range.


• Prime Number Check (without built-in functions): A number is prime if it has
exactly two divisors: 1 and itself.
• Concurrency: By using multiple threads, the workload is distributed efficiently
across CPU cores.
• Synchronization: A mutex (std::mutex) ensures safe access to the shared list of
prime numbers.

Algorithm:

Step 1: Input the Range

1. Read two integers n and m (start and end of the range).


2. If n > m, print "Invalid range" and terminate the program.

Step 2: Multi-Threading Setup

3. Create two threads:


o First thread checks primes in the range [n, (n + m) / 2].
o Second thread checks primes in the range [(n + m) / 2 + 1, m].
4. Start both threads to execute prime number checking concurrently.

Step 3: Prime Number Calculation

5. Each thread checks numbers in its assigned range:


o A number is prime if it is greater than 1 and has no divisors other than 1 and itself.
o If a number is prime, store it in the global primes[] array.

Step 4: Merge Results and Display Output

6. Wait for both threads to complete execution using join().


7. Print all stored prime numbers.
Coding:

#include <iostream>
#include <thread>

using namespace std;

const int MAX = 100000;


int primes[MAX], prime_count = 0;
int n, m;

bool isPrime(int num) {


if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}

void findPrimes(int start, int end) {


for (int i = start; i <= end; i++) {
if (isPrime(i)) {
primes[prime_count++] = i;
}
}
}

int main() {
cin >> n >> m;

if (n > m) {
cout << "Invalid range" << endl;
return 0;
}

thread t1(findPrimes, n, (n + m) / 2);


thread t2(findPrimes, (n + m) / 2 + 1, m);

t1.join();
t2.join();

for (int i = 0; i < prime_count; i++) {


cout << primes[i] << endl;
}

return 0;
}
Output:
Result:
Thus, the program correctly finds and displays all prime numbers within the given range
using optimized multi-threading.

You might also like