Posts

Showing posts from June, 2015

Prime Number Program in Java

Prime number is a number which is divisible by itself. We can write this program in multiple ways but it will reduce the performance for  larger numbers. Here we define one of faster and optimised way to check if number is prime or not. public boolean isPrime( int value) {           if(value == 2)                    return true;            if (value % 2 == 0)                    return false ;          for ( int j = 3; j <= Math.sqrt(value); j+=2) {                if (value % j == 0) {                        return false ;               }         }         return true ; } In this function, we first check if number is divisible by 2 or not. If not then no need to check with any other even numbers, So in for loop we increment value by 2. We use sqrt(value) as upper limit as if value is multiple of two number like a and b, then one of this number will be always less than square root value. So by using sqrt as upper limit, we will redu

Cross River puzzle

Two boys want to cross a river. Only one boat is present on the riverside that can carry only one person at a time. However, they still manage to cross the river. How is it possible ?