Monday, November 28, 2016

Print All Prime Numbers between 1-500 Using Java

Prime numbers are those numbers which do not have any factor except themselves. So any number which can't be divided by any other number except itself is a Prime Number. So, how do we identify Prime Numbers ? There are many ways to do so but as usual we'll go with the simplest and the easiest one. We are going to print all the prime numbers between 1 to 500. So how do we do it. Below is the code.



This is how it works. 

We just need to check the reminder of  the n/2 ( where n is the number under test) by all the numbers before that and if they leave the remainder as 0 that means the number is not prime. 

For example if the number under test is 19, so dividing 19/2=9.5 and if we keep dividing 9.5 by all the numbers from 2 to 9, there is always a remainder and hence the number is Prime. 

So using the for loop we are doing this check for all the numbers from 1 to 500. So any number which leaves a remainder is prime and the one which doesn't is not a Prime. 

Try it yourself. Also try to find more easier methods is you feel are better and faster, do share them.

Cheers !!

0 comments:

Post a Comment