0

a bit confuse about this java code

import java.util.Scanner; class PrimeCheck { public static void main(String args[]) { int temp; boolean isPrime=true; Scanner scan= new Scanner(System.in); System.out.println("Enter any number:"); //capture the input in an integer int num=scan.nextInt(); scan.close(); for(int i=2;i<=num/2;i++) { temp=num%i; if(temp==0) { isPrime=false; break; } } //If isPrime is true then the number is prime else not if(isPrime) System.out.println(num + " is a Prime Number"); else System.out.println(num + " is not a Prime Number"); } } ques : I am a bit confuse about the (for loop) why there is a i<=num/2 .. why num is divided by 2 .. like if my num is 10 diving it would be 5 which is a primal number right? while 10 is not.n on the next line num variable shouldn't be effected. but sill why divide by2

24th Jul 2020, 4:31 PM
Alapottra Chakma
Alapottra Chakma - avatar
5 Respostas
+ 1
Every divisor greater than 1/2 of a number obviously cannot be a factor of it*. So for the 10, 10/2 = 5 will also be evaluated, but not the 6. edit: * except itself, which is excluded for prime numbers
24th Jul 2020, 4:41 PM
Sandra Meyer
Sandra Meyer - avatar
+ 1
because after num/2 result of num%i will not be 0 13 = 2x6 +1 13 = 1x7 +6 13 = 1x8 +5 13 = 1x9 +4 13 = 1x10+3
25th Jul 2020, 7:40 AM
zemiak
0
so can i use i<= num /i instead of 2..since the value is same?
25th Jul 2020, 10:46 AM
Alapottra Chakma
Alapottra Chakma - avatar
0
No, because it will not keep the value 2, it is increased each iteration.
25th Jul 2020, 11:40 AM
Sandra Meyer
Sandra Meyer - avatar
0
ohh.. gottcha
25th Jul 2020, 11:41 AM
Alapottra Chakma
Alapottra Chakma - avatar