Tutorialspoint
Problem
Solution
Submissions

Twin Prime Numbers Under 100

Certification: Basic Level Accuracy: 100% Submissions: 2 Points: 5

Write a C# program to find and print all twin prime numbers under 100. Twin primes are pairs of prime numbers that differ by 2. For example, (3, 5), (5, 7), and (11, 13) are twin prime pairs.

Example 1
  • Input: limit = 20
  • Output: [(3, 5), (5, 7), (11, 13), (17, 19)]
  • Explanation:
    • Step 1: Find all prime numbers up to 20 using the Sieve of Eratosthenes.
    • Step 2: Initialize an empty list to store twin prime pairs.
    • Step 3: Iterate through the list of primes and check for pairs that differ by 2.
    • Step 4: The prime numbers under 20 are: 2, 3, 5, 7, 11, 13, 17, 19.
    • Step 5: The twin prime pairs are: (3,5), (5,7), (11,13), and (17,19).
Example 2
  • Input: limit = 10
  • Output: [(3, 5), (5, 7)]
  • Explanation:
    • Step 1: Find all prime numbers up to 10 using the Sieve of Eratosthenes.
    • Step 2: Initialize an empty list to store twin prime pairs.
    • Step 3: Iterate through the list of primes and check for pairs that differ by 2.
    • Step 4: The prime numbers under 10 are: 2, 3, 5, 7.
    • Step 5: The twin prime pairs are: (3,5) and (5,7).
Constraints
  • 2 ≤ limit ≤ 10⁵
  • Time Complexity: O(n * log(log n))
  • Space Complexity: O(n)
NumberVariables and Data TypesIBMPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the Sieve of Eratosthenes to find all prime numbers up to the limit
  • Scan through the list of primes and identify pairs that differ by 2
  • Store these pairs as twin primes
  • Remember that the smallest prime number is 2, but it doesn't have a twin
  • Return the result as a list of tuples

Steps to solve by this approach:

 Step 1: Create a boolean array to mark non-prime numbers using the Sieve of Eratosthenes.
 Step 2: Mark all multiples of each prime number as non-prime.
 Step 3: Initialize an empty list to store twin prime pairs.
 Step 4: Iterate through the array and find numbers p where both p and p+2 are prime.
 Step 5: Add each twin prime pair to the result list and return it.

Submitted Code :