197k views
2 votes
Write a multi-threaded program that outputs prime numbers. The program should work as follows: the user will run the program and enter a number on the command line. The program creates a thread that outputs all the prime numbers less than or equal to the number entered by the user. Also, create a separate thread that outputs this subset of the above primes that have the following property: the number that is derived by reversing the digits is also prime (e.g., 79 and 97).

2 Answers

3 votes

Final answer:

A multi-threaded program can be written in a programming language like Java to output prime numbers. The program will take a number as input from the user and create two separate threads. The first thread will output all the prime numbers less than or equal to the number entered, while the second thread will output the subset of these primes that have the property of being prime when their digits are reversed.

Step-by-step explanation:

A multi-threaded program can be written in a programming language like Java to output prime numbers. The program will take a number as input from the user and create two separate threads. The first thread will output all the prime numbers less than or equal to the number entered by the user, while the second thread will output the subset of these primes that have the property of being prime when their digits are reversed.

The program can be implemented using a function to check if a number is prime and another function to reverse the digits of a number. The first thread can iterate from 2 to the input number, checking if each number is prime, and output the prime numbers. The second thread can then take the output of the first thread, reverse each number, and check if the reversed number is also prime.

This multi-threaded program allows for parallel processing, where the first thread can find prime numbers and output them, while the second thread can simultaneously check the property of reversed primes. This can help in improving the efficiency of the program and make it faster.

User Veeru
by
5.3k points
5 votes

Answer:

The programming code can be found in the explanation part, please go through it.

Step-by-step explanation:

Code:

#include<stdio.h>

#include<stdlib.h>

#include <pthread.h>

// function check whether a number

// is prime or not

int isPrime(int n)

{

// Corner case

if (n <= 1)

return 0;

// Check from 2 to n-1

for (int i = 2; i < n; i++)

if (n % i == 0)

return 0;

return 1;

}

void* printPrimes(void *vargp)

{

int *n = (int *)vargp;

int i=0;

for (i=2;i<=n;i++)

{

if (isPrime(i)) printf("%d\\", i);

}

}

// Driver Program

int main(int argc, char* argv[])

{

int n = atoi(argv[1]);

pthread_t tid;

pthread_create(&tid, NULL, printPrimes, (void *)n);

pthread_exit(NULL);

return 0;

}

User Dandong Wang
by
4.9k points