PRIME NUMBER(the if function and being divided by 2) - java

Hi I'm having a little problem about prime function.
public static boolean isPrime(long num) {
for (long i=3; i <num/2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
I don't understand why it has to be num/2 and the if(num % i == 0).
so does it mean that if
num = 10 and i = 4 which would result to 2. makes 4 a prime number?
sorry if it's a stupid question, I just started coding \m/
edit: also, can someone explain the if(num % 1 ==0)

if you want to write a code to check whether is it is prime number or not then you need to change loop initialization.
long i=3 --> long i=2. Because prime number should not be divisible by any number other than 1. So you should start divide the number by 2,

Related

Basic Java - Finding if a number is a prime number using while loop

I have a question regarding an answer that was given here a while ago.
I came up with the same answer myself in the code attached but I'm trying to understand why do I need to divide the input number by 2 (line 10), and not just let the loop run its course till the value of the input number achieved.
1 import java.util.Scanner;
2 public class numIsPrime {
3 public static void main(String[] args) {
4 Scanner sc = new Scanner(System.in);
5 int i = 2;
6 boolean isPrime = true;
7 System.out.println("Enter a number");
8 int num = sc.nextInt();
9
10 while (i < num ) // (i <= num / 2)
11 {
12 if (num % i == 0)
13 isPrime = false;
14 i++;
15 }
16
17 if (isPrime)
18 System.out.println(num + " is a prime number");
19 else // !isPrime
20 System.out.println(num + " isn't a prime number");
21
22 }
23 }
This is the simplest way to calculate if an integer n is probably a prime:
public static boolean isPrime (int n) {
if (n < 2) return false;
BigInteger bigInt = BigInteger.valueOf(n);
return bigInt.isProbablePrime(100);
}
You can insert this function call in a loop where you can pass a new number every iteration. I am using the implementation of BigInteger provided by Java to do the calculation, rather than writing my own. UNLESS this is a homework and you are required to write your own algorithm, I would use this solution.
This base method can then be used for calculating other types of prime numbers. A complete answer can be found here.
UPDATE:
The int parameter in BigInteger.isProbablePrime(int) is a measure of the uncertainty that the caller is willing to tolerate. The larger the number, the "slower" it executes (but the more certain it is). Also, going back to the original question (already answered in the OP's comments section):
why do I need to divide the input number by 2 (line 10), and not just
let the loop run its course till the value of the input number
achieved.
This is an optimization that will make your evaluation run twice as fast. For example, suppose an evaluation of n integers take 10 minutes to complete, excluding even numbers should take half the time. That's a significant improvement. Although you should not optimize prematurely, these sort of optimizations should be done right from the get go. Basically, we all know that even numbers are not prime, so why evaluate it? You want to evaluate unknowns. In my solution, I only evaluate values greater than 2 because by definition, values less or equal to 2 are not prime. I am merely solving that by definition or by mathematical properties.
As mentioned in the comments, dividing by 2 is a simplest optimization to reduce the number of checks, however, existing code has a few issues (e.g. returning true for 0 and 1 which are NOT prime numbers) and may be further optimized:
break/end the loop as soon as isPrime is set to false
skip even numbers by incrementing by 2
calculate until i * i <= num
If this limit is reached, it means that no factor i of num has been found in the range [2, num/i], therefore by definition of the prime numbers, all the remaining numbers in the range [num/i, num] are neither the factors of num, and therefore num is prime.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2);
int i = 3;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += 2; // skip even numbers
}
if (isPrime)
System.out.println(num + " is a prime number");
else
System.out.println(num + " isn't a prime number");
More optimizations are possible if the divisibles of 3 (except 3) are excluded similar to the exclusion of even numbers, then the search continues from 5 and the candidates for primality comply with 6n ± 1 rule (e.g., 5 = 6 - 1, 7 = 6 + 1, 11 = 12 - 1, 13 = 12 + 1, etc.):
boolean isPrime = num > 1 && (num % 2 != 0 || num == 2) && (num % 3 != 0 || num == 3);
int i = 5;
int d = 2;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += d; // check only non-even numbers
d = 6 - d; // switch 2 to 4 and back to 2
}

Why doesn't my Fermat's primality test method work?

I'm trying to implement a method which checks any integer and returns true if it's prime using Fermat's primality test.
I divided the problem depending on whether the input is less than 40 or not. If the input is less than 40 then I apply the test for every integer up until n-1. Else, if the integer is greater than 40 then the test is applied for every integer up until 40. However, it fails for some primes.
public static boolean isPrime (double n){
int counter=0;
boolean isPrime=false;
if(n<40) {
for (int a = 2; a < n - 1; a++) {
if (Math.pow(a, n - 1) % n == 1) counter++;
}
if (counter == n - 3) isPrime = true;
}
else {
for (int a = 2; a <= 40; a++) {
if (Math.pow(a, n - 1) % n == 1) counter++;
}
if (counter == 39) isPrime = true;
}
return isPrime;
}
Is it a logical issue or something else?
Math.pow works on doubles and the result is only approximate. Modulo on the other hand works on ints which have a range up to a little over 2 billion, is your pow producing some numbers larger than that by any chance? (17^18 seems to be a sure bet for 19...)
So how to fix this:
you can implement your own pow(a,b,n) (power modulo n) using multiplication and modulo on integers. That should work correctly. Make a function to raise a to power b using a series of multiplications, apply %n to the intermediate result after each step...

Power of two failed to pass the test

Isn't this one way to test whether a number is a power of 2?
boolean isPowerOfTwo(int n) {
return (n%2==0);
}
Are you sure that you are checking power of 2? Rather, being checked divisible with 2. If you are serious, use the piece of cake snippet
return n > 0 && ((n & -n) == n);
The second way,
private static boolean powerOf2(int num)
{
if(num <= 0){
return false;
}
while(num > 1)
{
if(num % 2 != 0)
{
return false;
}
num = num / 2;
}
return true;
}
That function checks whether or not an integer is even (i.e divisible by 2), not whether or not the integer is a power of 2.
To check if a number is a power of 2, you should look at its bits. ints that are a power of 2 will have one bit set to 1 and all others set to 0.
boolean isPowerOf2(int i) {
return Integer.bitCount(i) == 1;
}
The % is the modulo operator, meaning the remainder after division. your method checks if the int n is divisible by 2

I don't understand this 'for' loop for prime number validation in Java

I don't understand this 'for' loop in Java
This loop is just to check if a number is prime or not. I understand the first statement because 1 is not a prime number but it's what happens in the 'for' statement. Why is 'primeNumber' being divided by two and why is the second 'if' calculating for a remainder of zero? how does this code help to confirm a prime number? what is it doing?
public static boolean isPrime (int primeNumber) {
if (primeNumber == 1) {
return false;
}
for (int primeDivider=2; primeDivider <= primeNumber/2; primeDivider++) {
if (primeNumber % primeDivider == 0) {
return false;
}
}
return true;
}
A prime number can only be divided by itself and one. 7 is prime because only 1 and 7 divide into 7. Also 8 is not prime because as well as 1 and 8, both 2 and 4 divide into 8.
Look at the for loop and see what values primeDivider takes: 2, 3, 4, 5, ... The loop tries each of these in turn to see if it divides into the number you are testing. If it divides evenly, with a remainder 0, then the number being tested is not prime and the method returns false. If none of the numbers divide, then the number being tested in prime and the method returns true. As an aside, primeNumber is a bad variable name. Something like possiblePrime would be better. The number being tested might not be prime.
The primeDivider sequence stops at half the number being tested. If a number is not prime (a composite number) then at least one of its divisors is guaranteed to be less than or equal to half the number.
As others have said, this is not a very efficient test. Here is a slightly more efficient version for you to study:
public static boolean isPrime (int possiblePrime) {
// Test negatives, zero and 1.
if (possiblePrime <= 1) {
return false;
}
// Test even numbers
if (possiblePrime % 2 == 0) {
// 2 is the only even prime.
return possiblePrime == 2;
}
// Test odd numbers >= 3.
int limit = possiblePrime / 2;
for (int primeDivider = 3; primeDivider <= limit; primeDivider += 2) {
if (possiblePrime % primeDivider == 0) {
return false;
}
}
// Only prime numbers reach this point.
return true;
}
By treating odd and even numbers separately, you can catch all the even numbers with a single test and by stepping primeDivider by 2 each time, roughly halve the time taken for odd numbers.
As billjamesdev says, that can be made even more efficient by using:
int limit = (int)Math.floor( Math.sqrt( possiblePrime ));
A composite number will always have a divisor, other than 1, less than or equal to its square root.

Print every prime number before N number

Hey I am beginning to program using java and my teacher used this example in class for our homework which was to create a java program that prints out every prime number before reaching the upper limit that the user inputs. I am not understanding the second part and wondering if someone could help explaining it to me.
import java.util.Scanner;
public class Primes {
public static void main(String args[]) {
//get input for the upper limit
System.out.println("Enter the upper limit: ");
//read in the limit
int limit = new Scanner(System.in).nextInt();
//use for loop and isPrime method to loop through until the number reaches the limit
for(int number = 2; number<=limit; number++){
//print prime numbers only before the limit
if(isPrime(number)){
System.out.print(number + ", ");
}
}
}
//this part of the program determines whether or not the number is prime by using the modulus
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
I guess that what you mean by second part is the isPrime method.
What he is doing is using '%' operator which returns the integer remainder of the division between 'number' and 'i'. As a prime number is just divisor for itself and the number 1, if the remainder is 0 it means is not a prime number. Your teacher is looping with the 'i' variable until the limit number and checking if any of the numbers is prime by looking the result of the % operation.
Hope this is helpful for you!!
In the second part
if(number%i == 0)
% usually gives you a remainder if there is.
eg
5 % 2 gives 1
4 % 2 gives 0
for(int i=2; i<number; i++)
Here you are looping through from 2 to the number. Since all numbers are divisible by 1 you start from 2.
Also you stop before number (number -1) since you dont want to check if the number is divisible by itself (because it is).
If a number is divisible by any other number other than 1 and itself (number from 2 to number -1) then it is not a prime number.
Just a short (not efficient) reference for finding prime numbers if you need it:
int upperLimit = 30; //Set your upper limit here
System.out.println(2);
for(int i = 2; i < upperLimit; i++)
for(int j = 2; j < i; j++)
if(i % j == 0 && i != 2)
break;
else if(j == i - 1)
System.out.println(i);

Categories