Primes A prime number is an integer that has exactly two factors: one, and itsel
ID: 3748216 • Letter: P
Question
Primes
A prime number is an integer that has exactly two factors: one, and itself. The number 1, however, is not considered to be prime. So the first few prime numbers are 2, 3, 5, 7, 11, 13.
Define a helper function using the symbolic operator notation slash-question-mark: (/?). This can be used as an infix operator to determine whether a number is divisible by another number (with no remainder). It returns a Boolean. For example:
ghci> 3 /? 2
False
ghci> 18 /? 3
True
ghci> 18 /? 4
False
Next, you can define isPrime n. It can check whether any number in the range [2..n-1] divides n. (It also must ensure that n > 1.)
Finally, a twin prime is a pair of neighboring odd numbers that are both primes. For example 11 and 13 are both prime so they are referred to as twins. Define a function isFirstTwinPrime n that determines whether n is the first of a pair of twin primes.
Explanation / Answer
# Checks prime numbers and returns twin prime numbers if they are.
// Author:dhanaji waghmare
import java.util.*;
class PrimeNumberCode {
static boolean isPrime(int n)
{
if (n <= 1) return false;
if (n <= 3) return true;
if (n /? 2 || n /? 3 )
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n /? i == 0 || n /? (i + 2) == 0)
return false;
return true;
}
// Returns true if n1 and n2 are twin primes
static boolean twinPrime(int n1, int n2)
{
return (isPrime(n1) && isPrime(n2) &&
Math.abs(n1 - n2) == 2);
}
public static void main(String[] args)
{
int n1 = 11, n2 = 13;
if (twinPrime(n1, n2))
System.out.println(" This are Twin Prime numbers");
else
System.out.println("These are Not Twin Prime numbers");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.