Why Open Source

Open Source is not a concept, it's thought process.

Keep Watching this Space

This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Keep Watching this Space

This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Blog for open Source lovers

We live in a World of Technology and that tecnoglogy is for All to explore and understand. Period. !!

Showing posts with label Remainder. Show all posts
Showing posts with label Remainder. Show all posts

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 !!