Find Twin Primes

Find the first 1000 twin prime numbers in Java using an isPrime function for the primality check and a value comparison between the prime numbers.
1. class TwinPrimes
2.{
3.        public static void main(String[] args)
4.        {
5.                int LastPrime = 1;
6.                for (int n = 0; n < 1000; n++)
7.                {
8.                        if (isPrime(n)) // We only care about prime numbers
9.                        {
10.                                if ((n - LastPrime) == 2) // If the difference between this prime and the last prime is 2
11.                                {
12.                                        System.out.println((n - 2) + " and " + n + " are twin primes"); // We have a twin prime
13.                                }
14.                                LastPrime = n; // Store the last prime so we can compare it to the next one
15.                        }
16.                }
17.        }
18. 
19.        public static boolean isPrime(int n)
20.        {
21.                if (n <= 1) // Not prime
22.                        return false;
23.                if (n == 2) // Prime
24.                        return true;
25.                if (n % 2 == 0) // Divisible by 2 means it's always not a prime
26.                        return false;
27.               
28.                // For all other numbers, test by checking the divisibility of the square root of the number
29.                int m = (int)Math.round(Math.sqrt(n));
30. 
31.                for (int i = 3; i <= m; i += 2)
32.                {
33.                        if (n % i == 0)
34.                        {
35.                                return false;
36.                        }
37.                }
38.                return true;
39.        }
40.}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top