Program: Determining Prime Numbers in Java

We will see the code in Java of how to determine a prime number, and then we will extend the same code to print prime number series till 100. A number is prime if it is divisible only by itself and 1.
public class PrimeNumbers {
 
    public static void main(String args[]){
        System.out.println(isPrime(7));
    }
 
     public static boolean isPrime(int number){
       for(int i = 2; i<=number/2; i++){
          if(number % i == 0){
               return false;
          } 
       }
       return true;
     }
}
We have created a method isPrime that returns true if the number is prime and it returns false if the number is not prime. As you can see we are running the for loop till number/2 as this is sufficient to determine if any other number divides it completely. (This will run the code faster) as we don’t need to check all the numbers. To Print all the prime numbers till 100. We can extend the above code to print prime numbers till 100.
public class PrimeNumbers {
 
    public static void main(String args[]){
         for(int i = 1; i<=100; i++){
             if(isPrime(i)){
                System.out.println(i);
             }
          }
    }
 
     public static boolean isPrime(int number){
       for(int i = 2; i<=number/2; i++){
          if(number % i == 0){
               return false;
          } 
       }
       return true;
     }
}
tgugnani: Web Stuff Enthusiast.