Friday, April 5

Generating & finding the given number is Prime Numbers or not in Java

Hi All,

A number is called as a prime if it has only two divisors. In other words, a number which is divided only by 1 and itself. i.e.; number of factors for a prime number should only be 5 (1 and itself).

Here I tried to get the number of prime numbers below a given number. and given number is prime number  or not .

import java.util.Scanner;

public class primeno {

    public static void main(String[] args) {

        System.out.println("Please enter the number: ");
        int limit = new Scanner(System.in).nextInt();
        System.out.println("Generate Prime numbers between 1 and " + limit);
        // loop through the numbers one by one
        for (int i = 1; i < limit; i++) {
            boolean isPrimeNumber = true;
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }
            // print the number if prime
            if (isPrimeNumber) {
                System.out.print(i + " ");
            }
        }
        System.out.println("\n\nFinding given number is prime number or not: ");
        if (finprime(limit)) {
            System.out.println("The given number is a prime number :-) " + limit);
        } else {
            System.out.println("The given number is not a prime number :-( " + limit);
        }
    }

    public static boolean finprime(int x) {
        int i;
        for (i = 2; i < x; i++) {
            if (x % i == 0) {
                break;
            }
        }
        if (i == x) {
            return true;
        }
        return false;
    }
}


out put:

~~~~~~


Please enter the number:
50
Generate Prime numbers between 1 and 50
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Finding given number is prime number or not:
The given number is not a prime number :-( 50

No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...