PRIME NUMBERS (java program) • boolean prime (int n): it returns true if n is pr
ID: 3826954 • Letter: P
Question
PRIME NUMBERS (java program)
• boolean prime (int n): it returns true if n is prime
• boolean twin-prime(int n): it returns true if n > 3 is prime and either n-2 or n+2 is also prime. Examples of twin primes: – 5,7 ; 11,13; 17,19; 29,31
• boolean m-prime(int n): it returns true if n is prime and it is of type 2(^m)-1. Examples of m (Mersennes) primes: – 3, 7, 31, 127
• Test your methods within a class and check that they work properly. Use the method prime(int n) in the implementation of the other 2 methods.
Explanation / Answer
PrimeWorld.java
import java.util.List;
import java.util.ArrayList;
public class PrimeWorld {
public boolean prime(int n)
{
// Corner cases
if (n <= 1) return false;
if (n <= 3) return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n%2 == 0 || n%3 == 0) return false;
for (int i=5; i*i<=n; i=i+6)
if (n%i == 0 || n%(i+2) == 0)
return false;
return true;
}
public boolean twinPrime(int n)
{
if (n <= 3)
return false;
return prime(n) && (prime(n-2) || prime(n+2));
}
public boolean mPrime(int n)
{
if (n <= 2)
return false;
if (! prime(n))
return false;
n = n+1;
// so far n is prime, we have reduced n by 1 and now check whether n is power of 2 using bit wise operator
return (n & (n - 1)) == 0;
}
public static void main(String[] args)
{
int n = 127;
PrimeWorld pw = new PrimeWorld();
List<Integer> primes = new java.util.ArrayList<>();
List<Integer> twinPrimes = new ArrayList<>();
List<Integer> mPrimes = new ArrayList<>();
for(int i = 0; i <= n; i++)
{
if (pw.prime(i))
{
primes.add(i);
}
if(pw.mPrime(i))
{
mPrimes.add(i);
}
if(pw.twinPrime(i))
{
twinPrimes.add(i);
}
}
System.out.println("Primes from 1 to 127: " + primes);
System.out.println("Twin Primes from 1 to 127: " + twinPrimes);
System.out.println("Mersennes Primes from 1 to 127: " + mPrimes);
}
}
Sample run
Primes from 1 to 127: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127]
Twin Primes from 1 to 127: [5, 7, 11, 13, 17, 19, 29, 31, 41, 43, 59, 61, 71, 73, 101, 103, 107, 109]
Mersennes Primes from 1 to 127: [3, 7, 31, 127]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.