Home » Freshers Interview » Prime number using Java

Prime number using Java

Write a Program to find if a number is prime or not ?

Solution :: Any number which is only divisible by 1 and the number itself is a prime number and it should not be divisible by any other number.

Program 1 ::
Algorithm ::
1. If num is 0,then it is not prime so return false
2. If num is 1 or 2 ,then it is prime so return true
3. In a loop try to divide the num with all the numbers less than the given input number ,if it is divisible by any
number then return false.
4. In rest cases return true.


output ::

Program 2

Algorithm ::
1. If num is 0,then it is not prime so return false
2. If num is 1 or 2 ,then it is prime so return true
3. In a loop try to divide the num with all the numbers less than the square root of given input number ,if it is divisible by any number then return false. Square root reduces the number of iteration.
4. In rest cases return true.


output ::


Leave a comment

Your email address will not be published. Required fields are marked *

1 + ten =