+ 1

# Can someone explain me how this is working it is checking prime numbers?

package javaapplication5; import java.util.Scanner; /** * * @author faakeer */ public class JavaApplication5 { /** * @param args the command line arguments */ ;public static void main(String[] args) { // TODO code application logic here Scanner Scan = new Scanner(System.in); int prime = 0; while (true) { System.out.println("Please enter a number"); prime = Scan.nextInt(); boolean isprime = true; for (int x = 2; x < (prime - 1); x++) { if ((prime % x) == 0) { isprime = false; } } if (isprime) { System.out.println("It is a prime"); } else { System.out.println("It is not a prime"); } } } }

15th Dec 2019, 6:33 AM
faakeer
0
Simple logic. Using module(%) operator to see if it is prime or not. If input is 11, 11%2 = 1 11%3 = 2 11%4 = 3 11%5 = 1 11%6 = 5 11%7 = 4 11%8 = 3 11%9 = 2 11%10 = 1 There is no "0" result so it is a prime number. But you don't need to check some numbers. To improve performance, you can edit loop condition like this: for(int x=2; x<=(prime/2); x++) Also you should use "break;" to cut loop when you saw "0" result. if((prime%x)==0){ isprime=false; break; }
15th Dec 2019, 7:52 AM
Mystic Life
+ 1
Thanks but in this coding prime numbers can find easily can someone explain the mechanism plz
15th Dec 2019, 8:07 AM
faakeer
+ 1
Thanks for clarifying
15th Dec 2019, 11:54 AM
faakeer
- 1
It is asking you to enter a number. (n) There is a boolean variable(isprime) that storing result. Assigned "true" at the beginning. Assuming the number is prime. Starting a loop to check all numbers between 2 to (n-1). If one of them divides the number(n) perfectly (if remaining is 0), then it is not a prime. So assigning false to the result variable. After loop ended, checking the result variable(isprime) and printing a text. This code is simple but you lose performance when you tried high numbers. There are better ways to find prime numbers.
15th Dec 2019, 8:44 AM
Mystic Life