Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PRIME NUMBERS (java) • boolean prime (int n): it returns true if n is prime • bo

ID: 3825431 • Letter: P

Question

PRIME NUMBERS (java)

• 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

PROGRAM CODE:

package com;

public class PrimeNumber {

   public boolean prime(int n)
   {
       if ((n == 1) || (n == 2))
   return true;
         
       for(int i=2; i<n/2; i++)
       {
           if(n%i==0)
               return false;
       }
       return true;
   }
  
   public boolean twin_prime(int n)
   {
       if(n>3)
       {
           if(prime(n) && (prime(n-2) || prime(n+2)))
               return true;
           else
               return false;
       }
       else return false;
   }
  
   public boolean m_prime(int n)
   {
       if(prime(n) && prime((int) (Math.pow(2, n)-1)))
       return true;
       else return false;
   }
  
   public static void main(String[] args) {
       PrimeNumber number = new PrimeNumber();
       System.out.println("Is 23 prime? " + number.prime(23));
       System.out.println("Is 98 prime? " + number.prime(98));
       System.out.println("Is 123 prime? " + number.prime(123));
       System.out.println("Is 500 prime? " + number.prime(500));
       System.out.println("Is 7 twin prime? " + number.twin_prime(7));
       System.out.println("Is 5 M-primes? " + number.m_prime(5));
       System.out.println("Is 11 M-primes? " + number.m_prime(11));
   }

}

OUTPUT:

Is 23 prime? true
Is 98 prime? false
Is 123 prime? false
Is 500 prime? false
Is 7 twin prime? true
Is M-primes? true
Is M-primes? false

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote