

The prime number program is an indispensable part of learning Java. you need to check whether the entered number (or already defined in the program) has some divisor other than one and itself or not. However, the basic logic remains the same i.e. There are several ways of writing a program in Java that checks whether a number is prime on not. It is one of the basic concepts concerning the leading high-level, general-purpose programming language. One of the most frequently asked questions that any Java developer needs to answer is to write a prime number program in Java. All the prime numbers are shaded with a green background.Akhil Bhadwal | 13 Dec, 2022 Prime Number Program in Java ("*** Prime Numbers between 1 to N ***") Ģ 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 Bonus – Prime Numbers Chartīelow table contains the list of Prime Numbers from 1 to 100.
#Prime numbers java for loop code#
We can also use the while loop instead of for loop, let’s re-write the above code using while loop. Prime Number Program in Java using While Loop 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.Returns false when the remainder is zero.

Returns false when the number is less than or equal to 1.It returns boolean values based on the below criteria The checkPrime() method, checks whether the number passed is prime or not.Using Scanner get the input from the user and store it in the variable “number”.Scanner scanner = new Scanner(System.in) 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.Check whether the number is greater than 1, if the number is less than 1 then it cannot be a prime.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. 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).įor Example, Let’s take the number 19. 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. We all know that the prime numbers can only be divided by itself and 1. 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
