This lesson of Java programming language will teach you the coding to find out whether a given number is prime or not. Here we have used the 'for loop' statement and given the required condition for a prime number. As we know, a prime number is only divided by 1 and itself, in other words it has no other factorial other than 1 and the number itself.
Here, first make a class and named as "
and take an integer as num=11, and define an integer 'i' as the integer other
than 1 and the given number. That means, i>2 and i<num. Now apply this in
the "for loop" statement and define an integer n=num/i as given
below in the example. Now apply the "if" condition and if the
reminder of the earlier equation comes "0", then the result will be
not prime. Again the loop system will check the above condition until it has not
satisfied from the starting point(2) to the end(10). Here under this loop we
have to use the "break" statement for unnecessary checking
further one point where the reminder comes zero(0).
Now after checking the whole condition, if the reminders does not come "zero", then we have to again apply the "if" condition and check whether i=num or not. If it is true then number (num) is prime. As we have taken here as num=11, then after compiling and running the program, the result will show that num is prime number.
Here is the code program:
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: June 4, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles