Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Method Exercises: Find all twin prime numbers less than 100

Java Method: Exercise-16 with Solution

Write a Java method to find all twin prime numbers less than 100.

Pictorial Presentation:

Java Method Exercises: Display the current date and time

Sample Solution:

Java Code:

import java.util.Scanner;
public class Exercise16 {
 
 public static void main(String[] args) {

        for (int i = 2; i < 100; i++) {

            if (is_Prime(i) && is_Prime(i + 2)) {
                System.out.printf("(%d, %d)\n", i, i + 2);
            }
        }
    }

    public static boolean is_Prime(long n) {

        if (n < 2) return false;

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

            if (n % i == 0) return false;
        }
        return true;
    }

}

Sample Output:

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

Flowchart :

Flowchart: Find all twin prime numbers less than 100

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java method to display the current date and time.
Next: Java Number Exercises

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe