Java Program to Check Prime Number

What is a Prime Number?

A prime number is a number that is only divisible by 1 or itself. For example, 11 is only divisible by 1 or itself. Other Prime numbers 2, 3, 5, 7, 11, 13, 17....
Note: 0 and 1 are not prime numbers. 2 is the only even prime number.

Java Program to check whether number is prime or not

Program Logic:
  • We need to divide an input number, say 17 from values 2 to 17 and check the remainder. If remainder is 0 number is not prime.
  • No number is divisible by more than half of itself. So we need to loop through just numberToCheck/2 . If input is 17, half is 8.5 and the loop will iterate through values 2 to 8
  • If a numberToCheck is completely divisible by other number, flag isPrime is set to true and the loop is exited.
  1. public class PrimenumberToCheckCheck {
  2. public static void main(String[] args) {
  3. int remainder;
  4. boolean isPrime=true;
  5. int numberToCheck=17; // Enter the numberToCheckber you want to check for prime
  6. //Loop to check whether the numberToCheckber is divisible any numberToCheckber other than 1 and iteself
  7. for(int i=2;i<=numberToCheck/2;i++)
  8. {
  9. //numberToCheckber is dived by itself
  10. remainder=numberToCheck%i;
  11. System.out.println(numberToCheck+" Divided by "+ i + " gives a remainder "+remainder);
  12. //if remainder is 0 than numberToCheckber is not prime and break loop. Elese continue loop
  13. if(remainder==0)
  14. {
  15. isPrime=false;
  16. break;
  17. }
  18. }
  19. // Check value true or false,if isprime is true then numberToCheckber is prime otherwise not prime
  20. if(isPrime)
  21. System.out.println(numberToCheck + " is a Prime numberToCheckber");
  22. else
  23. System.out.println(numberToCheck + " is not a Prime numberToCheckber");
  24. }
  25. }

Output:

17 Divided by 2 gives a remainder 1
17 Divided by 3 gives a remainder 2
17 Divided by 4 gives a remainder 1
17 Divided by 5 gives a remainder 2
17 Divided by 6 gives a remainder 5
17 Divided by 7 gives a remainder 3
17 Divided by 8 gives a remainder 1
17 is a Prime Number
Check our program to Find Prime Numbers from 1 to 100

No comments:

Post a Comment