Monday, 18 September 2017

Check number is prime or not

To check the given number is prime or not.
Prime Numbers:
  • A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
  •  It means the remainder of divison of N with numbers from 2 to N/2 should be grater than zero.
Lets take 6  6%2=0, 6%3=0...from 2 to 3(2 to 6/2)
here remainder is zero. So 6 is not prime number.
Lets take 5 now
5%2=1
here remainder is greater than zero. So 5 is prime number.

      PrimeNumberCheck.java  
public class PrimeNumberCheck { public static void main(String[] args) { PrimeNumberCheck app = new PrimeNumberCheck(); System.out.println("Eneter number:"); Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); System.out.println(app.isPrime(number)); } private boolean isPrime(int number) { boolean isPrime = true; for (int i = 2; i <= number / 2; i++) { if (number % i == 0) { return false; } } return isPrime; } } /* ****** INPUT ******** 5 ******* INPUT ******** ****** OUTPUT ******** true ******* OUTPUT ******** */

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *