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.}
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top