Prime code in java

5 Different Prime Number Program in Java | Prime Numbers between 1 to 100

A Prime Number is a number which is greater than 1 and divisible by 1 and only itself. Some of the Prime Numbers are 2, 3, 5, 7, 11, 13, 17… In this Prime Number Program in Java, let’s take a look into the different prime number programs.

Is 0 a prime number?

0 is neither prime nor composite number, as per the definition, a prime number is a number with exactly two positive divisors , 1 and itself. Zero has an infinite number of divisors (we can divide 0 by all real numbers) Therefore, zero is not a Prime Number.

Is 1 a prime number?

1 is not considered as a Prime because it does not meet the criteria which is exactly two factors 1 and itself, whereas 1 has only one factor

Prime Number Program in Java using Scanner

We all know that the prime numbers can only be divided by itself and 1. Let’s understand the range to consider.

In general, a number cannot be divided by any number which is greater than itself and hence we can set the upper limit as to the number. Furthermore, we can limit the range by considering the fact that no number can have factors greater than the square root of the number (or) number by half (including the number itself).

For Example, Let’s take the number 19. It cannot be divided by any number greater than 19, 20 cannot divide 19 and range to consider is 19/2 which is 9.5 and hence we can consider the range between 2 to 9.

  • Get the number to check from the user.
  • Check whether the number is greater than 1, if the number is less than 1 then it cannot be a prime.
  • In an iterative loop, divide the number between the range 2 to number/2, and check if the remainder is not zero, if zero then the number is not a prime.
package com.javainterviewpoint; import java.util.Scanner; public class PrimeNumber1 < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.println("Enter a number check :"); int number = scanner.nextInt(); if(checkPrime(number)) System.out.println(number +" is a Prime Number"); else System.out.println(number +" is not a Prime Number"); >public static boolean checkPrime(int n) < if(n return true; > >
  • Using Scanner get the input from the user and store it in the variable “number”.
  • The checkPrime() method, checks whether the number passed is prime or not. It returns boolean values based on the below criteria
    • Returns false when the number is less than or equal to 1.
    • Returns false when the remainder is zero.
    • If the number is greater than 1 and it is not divisible any number within the range of 2 to number/2 then it returns true.

    Prime Number Program in Java using While Loop

    We can also use the while loop instead of for loop, let’s re-write the above code using while loop.

    We just need to make some minor modifications like the initialization of “i” [i=2] happens just before the start of the loop, incrementation of “i” [i++] happens inside the loop and of course, we need to change for loop into while loop.

    package com.javainterviewpoint; import java.util.Scanner; public class PrimeNumber2 < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.println("Enter a number check :"); int number = scanner.nextInt(); if(checkPrime(number)) System.out.println(number +" is a Prime Number"); else System.out.println(number +" is not a Prime Number"); >public static boolean checkPrime(int n) < if(n return true; > >

    Java program to find all Prime Numbers from array

    In this approach, let’s get the input from the user and store it in the array and find all the prime numbers from array.

    • Get the size of the array from the user and create an array to store the input numbers
    • Get the elements of the array from the user and store it in the array which is created in the previous step
    • Finally, iterate the array and pass each element to the checkPrime() method and perform the prime validation
    package com.javainterviewpoint; import java.util.Arrays; import java.util.Scanner; public class PrimeNumber3 < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.println("Enter the size of the array :"); int arraySize = scanner.nextInt(); int[] values = new int[arraySize]; System.out.println("Enter the elements of the array : "); for (int i = 0; i < arraySize; i++) < values[i] = scanner.nextInt(); >System.out.println("*** Printing the Prime Numbers ***"); for (int i = 0; i < arraySize; i++) < if (checkPrime(values[i])) < System.out.println(values[i]); >> > public static boolean checkPrime(int n) < if (n return true; > >
    Enter the size of the array : 5 Enter the elements of the array : 1 2 3 4 5 *** Printing the Prime Numbers *** 2 3 5

    Prime Numbers between 1 to 100 / List of Prime Numbers from 1 to 100

    Let’s print all the prime numbers between 1 to 100

    package com.javainterviewpoint; public class PrimeNumber4 < public static void main(String[] args) < System.out.println("*** Prime Numbers between 1 to 100 ***"); for (int i = 2; i < 100; i++) < if (checkPrime(i)) < System.out.print(i+" "); >> > public static boolean checkPrime(int n) < if(n return true; > >
    *** Prime Numbers between 1 to 100 *** 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

    Find all Prime Numbers between 1 to N

    • Get the upper limit from the user and store it in the variable “N”
    • Start the loop from 2 to N, for each iteration increment the loop by 1
    • In the checkPrime() method, we have used a boolean flag. It will be set to false when the number is less than 1 or if the number is divisible by number/2.
    • Validate the boolean returned by the checkPrime() and print the number if the boolean returned is true.
    package com.javainterviewpoint; import java.util.Scanner; public class PrimeNumber5 < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.println("Enter the Upper limit :"); int N = scanner.nextInt(); System.out.println("*** Prime Numbers between 1 to N ***"); for (int i = 2; i > > public static boolean checkPrime(int n) < boolean flag = true; if(n > return flag; > >
    Enter the Upper limit : 55 *** Prime Numbers between 1 to N *** 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53

    Bonus – Prime Numbers Chart

    Below table contains the list of Prime Numbers from 1 to 100. All the prime numbers are shaded with a green background.

    Prime Numbers Chart

    Leave a Reply Cancel reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Источник

    Prime Number Program in Java

    One of the most frequently asked questions that any Java developer needs to answer is to write a prime number program in Java. It is one of the basic concepts concerning the leading high-level, general-purpose programming language.

    There are several ways of writing a program in Java that checks whether a number is prime on not. However, the basic logic remains the same i.e.; you need to check whether the entered number (or already defined in the program) has some divisor other than one and itself or not.

    The prime number program is an indispensable part of learning Java. Hence, most of the great books on Java covers it. Before moving forward to discuss the prime number program in Java, let’s first understand the concept of prime numbers and their importance.

    Prime Numbers – The Definition and Importance

    Any number that is only divisible by one other than itself is known as a primary number. 3, 5, 23, 47, 241, 1009 are all examples of prime numbers. While 0 and 1 can’t qualify for being a prime number, 2 is the only even prime number in the entire infinitely long set of prime numbers.

    Prime numbers exhibit a number of odd mathematical properties that make them desirable for a wide variety of applications, many of which belongs to the world of information technology. For example, primes find use in pseudorandom number generators and computer hash tables.

    There are several instances in the history of using encryption for hiding information in plain sight. Amazingly, it is the process of using prime numbers to encode information.

    With the introduction of computers, modern cryptography was introduced. It became feasible to generate complex and longer codes that were much, much difficult to crack.

    Most of the modern computer cryptography is dependent on making use of prime factors of large numbers. As prime numbers are the building blocks of whole numbers, they are of the highest importance to number theorists as well.

    Prime Number Program in Java

    As already mentioned, there are several ways of implementing a prime number program in Java. In this section, we’ll look at three separate ways of doing so, as well as two additional programs for printing primes.

    Type 1 – A Simple Program With No Provision for Input

    This is one of the simplest ways of implementing a program for checking whether a number is a prime number or not in Java. It doesn’t require any input and simply tells whether the defined number (by the integer variable n) is a prime number or not. Here goes the code:

    public class PrimeCheck < public static void main(String args[])< int i,m=0,flag=0; int n=3; m=n/2; if(n==0||n==1)< System.out.println(n+" is not a prime number."); >else < for(i=2;i<=m;i++)< if(n%i==0)< System.out.println(n+" is not a prime number."); flag=1; break; >> if(flag==0) < System.out.println(n+" is a prime number."); >> > >

    Type 2 – A Program in Java Using Method (No User Input Required)

    This Java code demonstrates the implementation of a prime number program that uses a method. Like the program mentioned before, it doesn’t ask for any user input and works only on the numbers entered to the defined method (named checkPrime) in the program. Here is the code:

    public class PrimeCheckUsingMethod< static void checkPrime(int n)< int i,m=0,flag=0; m=n/2; if(n==0||n==1)< System.out.println(n+" is not a prime number."); >else < for(i=2;i<=m;i++)< if(n%i==0)< System.out.println(n+" is not a prime number."); flag=1; break; >> if(flag==0) < System.out.println(n+" is a prime number."); >> > public static void main(String args[]) < checkPrime(1); checkPrime(3); checkPrime(17); checkPrime(20); >>

    One is not a prime number.
    3 is a prime number.
    17 is a prime number.
    20 is not a prime number.

    Type 3 – Prime Number Program in Java Using Scanner Class

    This Java program is similar to the aforementioned program. However, this program prompts for user input. Here goes the code:

    import java.util.Scanner; import java.util.Scanner; public class PrimeCheckUsingMethod2 < public static void main(String[] args) < Scanner s = new Scanner(System.in); System.out.print("Enter a number: "); int n = s.nextInt(); if (isPrime(n)) < System.out.println(n + " is a prime number."); >else < System.out.println(n + " is not a prime number."); >> public static boolean isPrime(int n) < if (n for (int i = 2; i < Math.sqrt(n); i++) < if (n % i == 0) < return false; >> return true; > > )

    Sample Output:

    Enter a number: 22
    22 is not a prime number.

    [Bonus Program] Type 4 – A Program in Java to Print Prime Numbers from 1 to 100

    Prime Number Program in Java Using Scanner Class and For Loop

    This code will demonstrate a Java program capable of printing all the prime numbers existing between 1 and 100. The code for the program is:

    class PrimeNumbers < public static void main (String[] args) < int i =0; int num =0; String primeNumbers = ""; for (i = 1; i =1; num--) < if(i%num==0) < counter = counter + 1; >> if (counter ==2) < primeNumbers = primeNumbers + i + " "; >> System.out.println("Prime numbers between 1 and 100 are :"\n); System.out.println(primeNumbers); > >

    Prime numbers between 1 and 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

    [Bonus Program] Type 5 – A Program in Java to Print Prime Numbers from 1 to n (User Input)

    Prime Number Program in Java Using Scanner and For Loop

    This Java program prints all the prime numbers existing between 1 and n, where n is the number entered by the user. Here is the code:

    import java.util.Scanner; class PrimeNumbers2 < public static void main (String[] args) < Scanner scanner = new Scanner(System.in); int i =0; int num =0; String primeNumbers = ""; System.out.println("Enter a number:"); int n = scanner.nextInt(); scanner.close(); for (i = 1; i =1; num--) < if(i%num==0) < counter = counter + 1; >> if (counter ==2) < primeNumbers = primeNumbers + i + " "; >> System.out.println("Prime numbers between 1 and n are:"/n); System.out.println(primeNumbers); > >

    Sample Output:

    Prime numbers between 1 and 22 are:
    2 3 5 7 11 13 17 19

    Conclusion

    That was all about the prime number program in Java. No matter at what skill level a Java developer is, it is very important to be able to write a program concerning prime numbers, at least for checking whether a given number (or set of numbers) is a prime or not.

    Continued learning is very important for advancing in coding. A program that you are able to write now might be better when you write it after gaining new knowledge. If you’re looking to enhance your Java skill further, consider checking out some of the best Java tutorials.

    Do you know some fascinating ways of implementing a prime number program in Java? Care to share with us? Then you can do so by the comment window below. Thanks in advance.

    People are also reading:

    • Best Java Courses
    • Top 10 Java Certifications
    • Best Java Projects
    • Top Java Programming Interview Questions
    • Top 10 Java Frameworks
    • Best Way to Learn Java
    • Constructor in java
    • OOPs Concept in Java
    • Difference Between Java vs. Kotlin
    • Difference Between C++ and Java
    • How to Code a Game?

    Источник

    Java Program to Check Whether a Number is Prime or Not

    To understand this example, you should have the knowledge of the following Java programming topics:

    A prime number is a number that is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

    Example 1: Program to Check Prime Number using a for loop

    public class Main < public static void main(String[] args) < int num = 29; boolean flag = false; for (int i = 2; i > if (!flag) System.out.println(num + " is a prime number."); else System.out.println(num + " is not a prime number."); > >

    In the above program, for loop is used to determine if the given number num is prime or not.

    Here, note that we are looping from 2 to num/2. It is because a number is not divisible by more than its half.

    Inside the for loop, we check if the number is divisible by any number in the given range (2. num/2) .

    • If num is divisible, flag is set to true and we break out of the loop. This determines num is not a prime number.
    • If num isn’t divisible by any number, flag is false and num is a prime number.

    Example 2: Program to Check Prime Number using a while loop

    public class Main < public static void main(String[] args) < int num = 33, i = 2; boolean flag = false; while (i ++i; > if (!flag) System.out.println(num + " is a prime number."); else System.out.println(num + " is not a prime number."); > >

    In the above program, while loop is used instead of a for loop. The loop runs until i

    Источник

    Читайте также:  Java util concurrent set
Оцените статью