Question
Finding Mersenne Primes with BigInteger in Java I am trying to make a list of mersenne numbers (2^x-1) in my main, and then send those
Finding Mersenne Primes with BigInteger in Java
I am trying to make a list of mersenne numbers (2^x-1) in my main, and then send those to a method to check if it is a prime number. If it is a prime number, it is printed. I have already written a program using int/double that works, but when trying to write it using BigInteger it's not working. I think I have a logic error somewhere but I can't find it.
This is the BigInteger program I am trying to fix:
import java.util.Scanner; import java.math.BigInteger;
public class Primes { public static void main(String[]args) { for(int i=2;i<=10;i++) { String str = String.valueOf(i); BigInteger power = new BigInteger(str); BigInteger base = new BigInteger("2"); BigInteger one = new BigInteger("1"); BigInteger prime = base.pow(i); prime=prime.subtract(one); BigInteger send = BigInteger.valueOf(i); boolean check = isPrime(send); if(check==false) System.out.println(prime); } } public static boolean isPrime(BigInteger num) { boolean flag = true; BigInteger two = BigInteger.valueOf(2); BigInteger half = num.divide(two); int halfInt = half.intValue(); BigInteger compare = new BigInteger("0"); compare = num.add(BigInteger.ONE); for(BigInteger bi = BigInteger.valueOf(2);bi.compareTo(num)<=halfInt;bi=bi.add(BigInteger.ONE)) { BigInteger check = num.mod(two); int compareValue = check.compareTo(compare); if(compareValue==0) { flag= false; break; } } return flag; } }
And this is the program written with int/double to show you my logic:
import java.util.ArrayList; import java.util.Scanner; import java.math.*; import java.io.*; @SuppressWarnings("unused") public class Sandbox { public static void main(String[]args) { int min = 2, max = 10; for(int i = min;i<=max;i++) { double mersenne = Math.pow(2,i)-1; boolean check = isPrime(i); if (check == true) System.out.println(i+" "+mersenne); } } public static boolean isPrime(int num) { boolean flag = true; int half = num/2; for(int i = 2;i<=half;i++) { if(num%i==0) { flag=false; break; } } return flag; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started