Computer Science, asked by anurag171105, 5 months ago

Write a Program in Java to print all the Twin Prime numbers within a given range​

Answers

Answered by hadiya4212
5

Answer:

Note: Twin Prime numbers are a pair of numbers which are both prime and their difference is 2.

Example: Twin Prime numbers in the range 1 to 100 are :

(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73)

Programming Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

/**

* The class TwinPrimeRange inputs 2 numbers and prints all the

* twin prime numbers within that range

* @author : www.guideforschool.com

* @Program Type : BlueJ Program - Java

*/

import java.util.*;

class TwinPrimeRange

{

boolean isPrime(int n) //funton for checking prime

{

int count=0;

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

{

if(n%i == 0)

count++;

}

if(count == 2)

return true;

else

return false;

}

public static void main(String args[])

{

TwinPrimeRange ob = new TwinPrimeRange();

Scanner sc = new Scanner(System.in);

System.out.print("Enter the lower range : ");

int p = sc.nextInt();

System.out.print("Enter the upper range : ");

int q = sc.nextInt();

if(p>q)

System.out.println("Invalid Range !");

else

{

System.out.println("\nThe Twin Prime Numbers are : ");

for(int i=p; i<=(q-2); i++)

{

if(ob.isPrime(i) == true && ob.isPrime(i+2) == true)

{

System.out.print("("+i+","+(i+2)+") ");

}

}

}

}

}

Output:

Enter the lower range : 1

Enter the upper range : 200

The Twin Prime Numbers within the given range are :

(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73) (101,103) (107,109) (137,139) (149,151) (179,181) (191,193) (197,199)

Explanation:

hope this helps

Similar questions