Use Modulus Operator to Get Prime Numbers [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How would you modify the below to print out all prime numbers from 1-100? The below has an issue with the number 2 coming back as not prime. The if(i%number == 0) condition is met for the number 2 as 2%2 is returned as 0.
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
for(int i=1; i<=100; i++){
if(isPrime(i)){
System.out.println(i + " is a prime number");
}else{
System.out.println(i + " is not a prime number");
}
}
}
public static boolean isPrime(int number){
for(int i=2; i<=number; i++){
if(i%number == 0){
return false;
}else{
return true;
}
}
return false;
}
}

i<=number
You shouldn't be checking whether the number is divisible by itself.
You also have another problem:
}else{
return true;
}
You're returning true as soon as you find a single non-divisible number, even if it does have factors later.

Here is an algorithm for determining whether or not a number is prime.
Is the number less than 2? If so, return false.
Is the number 2 or 3? If so, return true.
Is the number 4? If so, return false.
Take the square root of the number, rounded up to the next integer. This is optional for small prime numbers, but speeds up the determination for larger numbers.
Loop from 5 to the square root of the number (or the number), incrementing by 2.
Divide the loop number by the prime numbers determined so far.
If the modulus of the division is zero, return false.
If the loop is completed, return true.

You've got a couple issues here. Firstly, when checking whether or not a number is prime, never check every number up to the actual number being checked for primality. A check of all primes up to the square root of the number will always be sufficient.
To fix that error look at your for loop condition and edit it accordingly:
for(int i=2; i<=number; i++)
Secondly, when a function returns it stops. Currently with your if/else statement:
if (i%number == 0) {
return false;
} else {
return true;
}
If this condition goes to the else statement even once it will return true, you want to make sure you only actually return true when you've checked all of the numbers you intend to.
Additionally I don't think you've carefully considered what you base case is. What you are saying with your last line is that if everything previously slipped through the cracks then it should assume the number isn't prime. Think about it and I'm sure you'll be able to figure it out.

This will work. 2 is a special case when testing for primes. If you start to search a larger and larger...you might want to look at the sieve of eratosphenes.
Every prime number is a multiple of another number. Take 3 for example. Using the sieve, if you find 3 to be prime it will then 'ignore' all multiples of 3 thus reducing the amount of time taken to find consequent primes. It speeds things up...ALOT :)
public class JavaApplication47 {
public static void main(String[] args) {
for(int i=1; i<=100; i++){
if(isPrime(i)){
System.out.println(i + " is a prime number");
}else{
// System.out.println(i + " is not a prime number");
}
}
}
public static boolean isPrime(int n) {
for(int i=2; 2*i<n; i++) {
if(n%i==0)
return false;
}
return true;
}
}
SIEVE EXAMPLE - NOT IMPLEMENTED - Can be used for reference and understanding.
static boolean [] allPrimes = new boolean[10000];
public static void fillTheSieve(){
Arrays.fill(allPrimes, true);
allPrimes[0] = allPrimes[1] = false; //1 and 0 are false. winning
for (int i = 2; i < allPrimes.length; i++) {
//check if prime, if so getmultiples and declae false
if(allPrimes[i]){
for (int j = 2; i*j<allPrimes.length; j++) {
allPrimes[i*j] = false;
}
}
}
}

The definition of a prime number specifically states that one cannot be a prime number.
That means that isPrime(1) should return false. Which your implementation does.
But isPrime(2) should return true. Which your implementation does not. It does not because (2 % 2 == 0) and you are checking all numbers from 2 to N, not from 2 to N-1. The last number, N, will always yield a zero remainder (N % N == 0)

Just a few things to think about when dealing with Primes. You can have a special case for 2 at the start (i.e. something like if(number == 2)...).
In addition to your error in checking all the way to i<=number consider only how far you need to go in order to be certain it is not prime, hints have already been given with i*i or Math.sqrt
Another thing in the increment i++ think about what that entails, I realize this is only for the first 100 primes but you should always be thinking about performance. Do you really have to check all numbers (2,3,4,5,6...) (hint: if you have checked if its divisible by 2 then you dont need to check for 4,6,8 etc..)
Finally with your return statements, consider using a boolean flag that you set to false/true only when you are positive the number is a prime or is not. And you only need to use 1 return statement.
Hope that helps.

Please try this
public static boolean isPrime(int number) {
for(int i = 2; i * i <= number; i++) {
if (i % number == 0) {
return false;
} else {
return true;
}
}
return true;
}

Related

Why is this program for finding Prime Factors of a number using Java not working?

I would like to know why this java program is not working to find the prime factors of a number. I have seen many solutions on this site and elsewhere but I want to know why this approach is not sufficient as it returns only 1 as an output? The first "if statement" handles numbers from 1 and lower to return -1 (invalid value), thanks.
public class PrimeFactors{
public static void main(String[] args) {
System.out.println(getPrimeFactors(4));
}
public static int getPrimeFactors(int number) {
if (number <= 1) {
return -1;
}
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
return i;
}
}
return number;
}
}
The code you have here is returning the value of i, which you have set to 1. You don't have enough understanding of how you would find a prime number based on your code. No matter what you put into your method, getPrimeFactors will either return -1 or 1, because of how your code is set up. The remainder when a number is divided by 1 is always 0, therefore it is always true, which will just return 1. And if the number is less than or equal to 1, it will return -1. Return number is essentially dead code unless you fix the syntax. Hope this helps you out!

How to determine if a number is prime

Okay my issue is less of how to figure out if a number is prime, because I think I figured that out, but more of how to get it to display properly.
Here's my code:
public static void main(String[] args) {
// Declare Variables
int randomNumbers = 0;
int sum = 0;
//Loop for number generation and print out numbers
System.out.print("The five random numbers are: ");
for (int i = 0; i <= 4; i++)
{
randomNumbers = (int)(Math.random()*20);
sum += randomNumbers;
if (i == 4) {
System.out.println("and " + randomNumbers + ".");
}
else {
System.out.print(randomNumbers + ", ");
}
}
//Display Sum
System.out.println("\nThe sum of these five numbers is " + sum + ".\n");
//Determine if the sum is prime and display results
for(int p = 2; p < sum; p++) {
if(sum % p == 0)
System.out.println("The sum is not a prime number.");
else
System.out.println("The sum is a prime number.");
break;
}
}
}
Now my problem is, if the number ends up being something like 9, it'll say it is a prime number, which it is not. I think the issue is that the break is stopping it after one loop so it's not incrementing variable p so it's only testing dividing by 2 (I think). But if I remove the break point it will print out "The sum is/is not a prime number" on every pass until it exits the loop. Not sure what to do here.
Your method for finding if your number is prime is the correct method.
To make it so that it does not consistently print out whether or not the number is prime, you could have an external variable, which represents whether or not the number is prime.
Such as
boolean prime = true;
for (int p = 2; p < sum; p++) {
if (sum % p == 0) {
prime = false;
break;
}
}
if (prime)
System.out.println("The sum is a prime number.");
else
System.out.println("The sum is not a prime number.");
By doing this method the program will assume the number is prime until it proves that wrong. So when it finds it is not prime it sets the variable to false and breaks out of the loop.
Then after the loop finishes you just have to print whether or not the number was prime.
A way that you could make this loop faster is to go from when p = 2 to when p = the square root of sum. So using this method your for loop will look like this:
double sq = Math.sqrt((double)sum);
for (int p = 2; p < sq; p++) {
//Rest of code goes here
}
Hope this helps
You need to store whether or not the number is prime in a boolean outside of the loop:
//Determine if the sum is prime and display results
boolean isPrime = true;
for(int p = 2; p < sum; p++) {
if(sum % p == 0){
isPrime = false;
break;
}
}
if(isPrime){
System.out.println("The sum is a prime number.");
} else {
System.out.println("The sum is not a prime number.");
}
You are right, currently your code tests dividing by two, and the break command is stopping after one loop.
After the first go of your loop (p==2), the break will always stop the loop.
The fastest fix to your code will change the loop part like this:
boolean isPrime=true;
for(int p = 2; p < sum; p++) {
if(sum % p == 0) {
isPrime=false;
System.out.println("The sum is not a prime number.");
break;
}
}
if (isPrime)
System.out.println("The sum is a prime number.");
This code can be improved for efficiency and for code elegance.
For efficiency, you don't need to check divisibility by all numbers smaller than sum, it's enough to check all numbers smaller by square-root of sum.
For better code, create a seperate function to test if a number is prime.
Here is an example that implements both.
// tests if n is prime
public static boolean isPrime(int n) {
if (n<2) return false;
for(int p = 2; p < Math.sqrt(n); p++) {
if(n % p == 0) return false; // enough to find one devisor to show n is not a prime
}
return true; // no factors smaller than sqrt(n) were found
}
public static void main(String []args){
...
System.out.println("sum is "+ sum);
if (isPrime(sum))
System.out.println("The sum is a prime number.");
else
System.out.println("The sum is not a prime number.");
}
Small prime numbers
Use Apache Commons Math primality test, method is related to prime numbers in the range of int. You can find source code on GitHub.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
// org.apache.commons.math3.primes.Primes
Primes.isPrime(2147483629);
It uses the Miller-Rabin probabilistic test in such a way that a
result is guaranteed: it uses the firsts prime numbers as successive
base (see Handbook of applied cryptography by Menezes, table 4.1 / page 140).
Big prime numbers
If you are looking for primes larger than Integer.MAX_VALUE:
Use BigInteger#isProbablePrime(int certainty) to pre-verify the prime candidate
Returns true if this BigInteger is probably prime, false if it's
definitely composite. If certainty is ≤ 0, true is returned.
Parameters: certainty - a measure of the uncertainty that the caller
is willing to tolerate: if the call returns true the probability that
this BigInteger is prime exceeds (1 - 1/2certainty). The execution
time of this method is proportional to the value of this parameter.
Next use "AKS Primality Test" to check whether the candidate is indeed prime.
So many answers have been posted so far which are correct but none of them is optimized. That's why I thought to share the optimized code to determine prime number here with you. Please have a look at below code snippet...
private static boolean isPrime(int iNum) {
boolean bResult = true;
if (iNum <= 1 || iNum != 2 && iNum % 2 == 0) {
bResult = false;
} else {
int iSqrt = (int) Math.sqrt(iNum);
for (int i = 3; i < iSqrt; i += 2) {
if (iNum % i == 0) {
bResult = false;
break;
}
}
}
return bResult;
}
Benefits of above code-:
It'll work for negative numbers and 0 & 1 as well.
It'll run the for loop only for odd numbers.
It'll increment the for loop variable by 2 rather than 1.
It'll iterate the for loop only upto square root of number rather than upto number.
Explanation-:
I have mentioned the four points above which I'll explain one by one. Code must be appropriately written for the invalid inputs rather the only for valid input. Whatever answers have been written so far are restricted to valid range of input in which number iNum >=2.
We should be aware that only odd numbers can be prime, Note-: 2 is the only one even prime. So we must not run for loop for even numbers.
We must not run for loop for even values of it's variable i as we know that only even numbers can be devided by even number. I have already mentioned in the above point that only odd numbers can be prime except 2 as even. So no need to run code inside for loop for even values of variable i in for.
We should iterate for loop only upto square root of number rather than upto number. Few of the answers has implemented this point but still I thought to mention it here.
With most efficient time Complexity ie O(sqrt(n)) :
public static boolean isPrime(int num) {
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
you can use the Java BigInteger class' isProbablePrime method to determine and print whether the sum is prime or not prime in an easy way.
BigInteger number = new BigInteger(sum);
if(number.isProbablePrime(1)){
System.out.println("prime");
}
else{
System.out.println("not prime");
}
You can read more about this method here https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#isProbablePrime%28int%29

Prime Number Calculator Not Working With Large Numbers

I am trying to print out all the prime factors of a number. My code is as follows:
public static boolean isPrime(long n){
long i = n;
while (i > 0){
if (n % i == 0 && !(i == 1 || i == n)){
return false;
}
i--;
}
return true;
}
public static void primeFactors(long n){
long i = n;
while (i > 0){
if (isPrime(i)){
System.out.println(i);
}
i--;
}
}
This code works for small numbers: 5, 5000,e.g. When I input 600851475143 to the method, my program runs and nothing is output. Why is this happening?
Your primality test function is horrible.
Quick win: count forwards not backwards. Currently you'll count through at lease half your number until you find a factor! That probably accounts for the delay you are observing.
Bit better: count odd numbers up to the square root.
Perhaps better still: count prime numbers up to the square root. precompute those using a sieve depending on the requirements.
The other answers have focused on your function isPrime, which is inefficient. I will instead focus on your function primeFactors which is incorrect. Indeed, you can see that it prints primes up to n in reverse order, rather than the prime factors of n. Instead, do
public static void primeFactors(long n) {
// Handle factors of 2
while (n%2==0) {
System.out.println(2);
n /= 2;
}
// Handle all odd prime factors except the largest
for (long p = 3; p*p <= n; p += 2) {
while (n%p == 0) {
System.out.println(p);
n /= p;
}
}
// Handle the largest prime factor
if (n > 1) {
System.out.println(2);
}
}
You might notice that isPrime is never used! In fact it is not needed: as long as they are removed as you find them, all of the numbers you print will be primes.
There are many possible improvements here, but this method is fast enough as-is. One simple way would be to compute an upper bound of Math.sqrt(n) and compare p to it rather than multiplying p by itself each time. You might also want to check for 0 and negative numbers, and possibly 1, depending on how you want to handle those numbers.
When given the input number 600851475143, your program is printing nothing because the way you check for prime numbers is slow. Given enough patience, your program will print something - but this could be hours, days, even years. You would need to come up with a better algorithm for this calculation.
Short answer: the program actually isn't terminating. The method that you are using is one of the most inefficient ways to check for primes. Check out the Sieve of Eratosthenes for an easy to understand, fairly efficient algorithm.
no need to check n numbers to check if n is prime or no, It's enough to start from 0 to n/2:
public static boolean isPrime(long n){
long i = 2;
while (i < n/2){
if (n % i == 0 ){
return false;
}
i++;
}
return true;
}
This will double performance
Although the number is not out of long primitive value range (9,223,372,036,854,775,807), you should use BigInteger since BigInteger has function for this purpose and I think it is more efficient then other implementations including yours.
new BigInteger(yourNumer).isProbablePrime(100) // returns true or false
Furthermore primality test is done by using many mathematical approaches and algorithms, there are some ways which runs faster for numbers < 64bit and there are some which are better to test much larger numbers. There some other ways here
Change your method to the following:
public static boolean isPrime(long num) {
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
Should be efficient enough.

Java program showing primes

I would like to have a program that show range in specific range and show "no primes" once only if there is no primes in that range like 24 to 28.
int count=0;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
count=0;
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0)
count++;
}
if(count==0)
System.out.println(prime);
}
if (count>0)
System.out.println("nope");
I have tried to put
if (count>0)
System.out.println("nope");
outside the loop,however it also prints when the range having primes.
How can i tackle it?
Keep one extra variable like noOfPrime, which will count the number of prime number with in a range. And increase by 1 if you found any prime, so that out side of loop you could determine the number prime number as well there is any prime number or not.
int count = 0;
int noOfPrime = 0;
...
for(prime = lowerLimit ;prime < upperLimit; prime++){
...
if(count==0){
System.out.println(prime);
noOfPrime+=1;
}
}
if(noOfPrime >0)
System.out.println("no primes);
First of all, your method for detecting primes is terrible. It works, but it's super slow. I'd suggest you look into using sieves if you want to improve that inner loop.
Secondly, what exactly are you trying to count? Right now your count variable stores the amount of divisors a number has, and then you set it to zero when you check the next number. How is that going to tell you anything about how many primes you have in a certain range? You can just do something like this:
notPrime = false;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0){
notPrime = true;
break;
}
if(notPrime)
break;
}
if(notPrime) System.out.println("There's a prime");
You could design a function to determine if a number is prime something like:
//checks whether an int is prime or not.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
and within a for loop, you call the function to each element of the interval:
for(int i=lowerLimit;i<=upperLimit;i++){
if (!(isPrime(i))){
System.out.println("nope");
break;
}
}
Sorry if I have some syntactic errr, I replied from the cell phone.
Everytime you get to the end of the outer loop and count is still 0, it means that you've found a prime number. So if this happens even once, then you're not going to print "nope" at the end. Use a boolean variable to keep track of whether or not you've seen a prime. Since this is homework, I'll let you figure out exactly how to use it. Hint: declare the boolean above both loops.

Nested "FOR-loops" not working

I am doing an excercise in the book "Java how to program". The excercise wants me to write a method that determines if a number is "prime". (A "Prime number" is a positiv integer which is only dividable with itself and 1). Then I am supposed to implement the method in an application that displays all integers up to 10 000.
I use "double-values" to test whether the remainder is 0 or not, to test dividability.
Anyway, I just don´t get the program to work, it displays all numbers fro 3, with an increement on how many times each number is displayed (3 44 555 etc). Can anyone please tell me what I´m doing wrong?
The code is the following:
public class Oppgave625
{
public static void main(String[] args)
{
for(double a = 2; a <= 10000; a++)
{
for(double b = 1; b < a; b++)
{
if (prime(a, b) !=0)
{
System.out.printf("%.0f ", prime(a, b));
}
}
}
}
static double prime(double x, double y)
{
if (x % y != 0)
{
return x;
}
else
{
return 0;
}
}
}
Use int instead. double is not good for this purpose
you might want to read this article to understand the use of the % Operator for floating point numbers.
Actually, there were many individual errors in here. I shortened the prime() function to the point where it was only a modulo op, so I was able to inline it. Second, I inverted the test so it checked for numbers that do not have a remainder, and continues to the next number as soon as it finds a divisor. Third, I changed b = 1 so that we do not check for numbers divisible by 1, because this would result to all numbers. Finally, I only print out the numbers for which we do not discover a divisor. The final result:
public static void main(String[] args) {
outer:
for (int a = 2; a <= 1000; a++) {
for (int b = 2; b < a; b++) {
if (a % b == 0) {
continue outer;
}
}
System.out.println(a);
}
}
Edit: I forgot to mention, I also changed the types from floats to ints, since I'm sure that's what you meant.
It's great that you posted sample code for this, but there are several things that are wrong:
you should not use a floating point type for this, but an int or a long. Floating point types should never be used for precise values.
you are making two calls to your prime function, effectively doubling the required steps
your prime function only tells you whether two numbers divide themselves evenly, it does not tell you whether one is a prime or not
for prime numbers, you should use a more efficient algorithm instead of calculating the same values over and over for each number. Look up Sieve of Eratosthenes.
You are approaching the problem like this: The number A is NOT prime, whenever i can find a number B that can divide A without a remainder.
Bur right now, you print out A whenever it is not dividable by B.
Instead you could say: whenever A not divisible by B, increase B. When i found a B to divide A, quit the inner loop, print nothing.
When i found no B, print A and quit loop.
Furthermore, you only have to test for divisibility of A until (a/2)-1.
A prime number is a number that is only divisible by one and itself. That is: one number. Your code is comparing two numbers as in the Euclidean algorithm for testing coprime-ness. This is very different than testing if a number is prime.
Your code should look something like this:
for i = 2 to 10,000 {
if( isPrime(i) ){
print i
}
}
function isPrime( int n ){
for i = 2 to n {
next if i == n
if( n % i == 0 ){
return 0;
}
}
return 1;
}
boolean isPrime = true;
for (int i = 2; i<=100; i++){
for(int j = 2; j<=i/2; j++){
isPrime = true;
if (i%j==0){
isPrime = false;
break;
}
}
if (isPrime){
Log.d("PrimeNumber",""+i);
}
}

Categories