Problem:
The largest known prime numbers are called the Mersenne Primes. They are of the form 2 power p - 1 where p is prime.
Solution:
package com.myprograms;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MersennePrime {
int n;
List<Integer> primeNumbers = new ArrayList<Integer>();
List<Integer> mersennePrimeNumbers = new ArrayList<Integer>();
public static void main(String[] args) {
MersennePrime mersennePrime = new MersennePrime();
mersennePrime.getTheNumber();
mersennePrime.findThePrimeNumbers();
mersennePrime.printThePrimeNumbers();
mersennePrime.findMersennePrime();
mersennePrime.printTheMersennePrimeNumbers();
}
public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the number");
n = s.nextInt();
s.close();
}
public void findMersennePrime(){
for(Integer i : primeNumbers){
mersennePrimeNumbers.add(((int)Math.pow(2, i)) - 1);
}
}
public void findThePrimeNumbers(){
for (int i = 2; i < n; i++) {
if(isPrime(i)){
primeNumbers.add(i);
}
}
}
public boolean isPrime(int number){
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
if(number%i == 0){
isPrime = false;
}
}
return isPrime;
}
public void printThePrimeNumbers(){
System.out.println("The prime numbers are " + primeNumbers);
}
public void printTheMersennePrimeNumbers(){
System.out.println("The mersenne prime numbers are " + mersennePrimeNumbers);
}
}
Output:
enter the number
20
The prime numbers are [2, 3, 5, 7, 11, 13, 17, 19]
The mersenne prime numbers are [3, 7, 31, 127, 2047, 8191, 131071, 524287]
No comments:
Post a Comment