Wednesday, 23 December 2015

Java Program For Find a Prime Number in different approches


 1st approach:

/*
 *
 * To Find the Prime Numbers 1 to 100 Numbers
 */

package com.onlinetutorialspoint.javaprograms;

public class PrimeNumberDemo1 {

    public static void main(String[] args) {
        int i = 0;
        int num = 0;
       
        String primeNumbers = "";

        for (i = 1; i <= 100; i++) {
            int counter = 0;
            for (num = i; num >= 1; num--) {
                if (i % num == 0) {
                    counter = counter + 1;
                }
            }
            if (counter == 2) {
               
                primeNumbers = primeNumbers + i + " ";
            }
        }
        System.out.println("Prime numbers from 1 to 100 are :");
        System.out.println(primeNumbers);
    }

}

output:
Prime numbers from 1 to 100 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97


2nd approach:



/*
 * To find the PrimeNumber by using Scanner Class
 */


package com.onlinetutorialspoint.javaprograms;

import java.util.Scanner;

public class PrimeNumberDemo2 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int i = 0;
        int num = 0;
        // Empty String
        String primeNumbers = "";
        System.out.println("Enter the value of n:");
        int n = scanner.nextInt();
        for (i = 1; i <= n; i++) {
            int counter = 0;
            for (num = i; num >= 1; num--) {
                if (i % num == 0) {
                    counter = counter + 1;
                }
            }
            if (counter == 2) {
                // Appended the Prime number to the String
                primeNumbers = primeNumbers + i + " ";
            }
        }
        System.out.println("Prime numbers from 1 to n are :");
        System.out.println(primeNumbers);
    }

}

output:

Enter the value of n:
34
Prime numbers from 1 to n are :
2 3 5 7 11 13 17 19 23 29 31

3rd approach:

/*
 *
 *  To check the Number is either Prime or Not
 *
 */


package com.onlinetutorialspoint.javaprograms;

import java.util.Scanner;

public class PrimeNumberDemo3 {
   
   
    public static void main(String args[])
       {       
        int temp;
        boolean isPrime=true;
        Scanner scan= new Scanner(System.in);
        System.out.println("Enter a number for check:");
        //capture the input in an integer
        int num=scan.nextInt();
        for(int i=2;i<=num/2;i++)
        {
               temp=num%i;
           if(temp==0)
           {
              isPrime=false;
              break;
           }
        }
        //If isPrime is true then the number is prime else not
        if(isPrime)
           System.out.println(num + " is Prime Number");
        else
           System.out.println(num + " is not Prime Number");
       }

}

output:

Enter a number for check:
67
67 is Prime Number








No comments:

Post a Comment