19 February 2014

Program to check if a number is Prime or not

Create a new Class with name Chk_prime :

import java.util.Scanner;
 

public class Chk_prime {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int rem=0,i=2;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number to check if it is prime : ");
        int num = sc.nextInt();
        System.out.println("You entered : "+num);
        if(num==2){
            System.out.print(num+" is even prime");
        }
        else{
        while(i<num){
            rem = num%i;
            if(rem==0){
                System.out.print(num+" is not prime");
            break;}
            else
                i++;
                    }
        if(rem!=0)
            System.out.print(num+" is prime");
        }
        }
    }


Output:(Click on image to enlarge)
Program-to-check-if-a number-is-Prime-or-not-output
(Comment if you have any doubts)

Contact Form

Name

Email *

Message *

Smooth Graphics Java

// Arrange Bricks in Game //java brick breaker game code without flickering // added game levels 1,2,3 in the game //java paddle ball ga...