The Artima Developer Community
Sponsored Link

Java Buzz Forum
How to Check if Given Number is Prime in Java - With Example

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Javin Paul

Posts: 1090
Nickname: javinpaul
Registered: Jan, 2012

Javin Paul is Java Programmer working on Finance domain.
How to Check if Given Number is Prime in Java - With Example Posted: Jan 25, 2014 9:58 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Javin Paul.
Original Post: How to Check if Given Number is Prime in Java - With Example
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Latest Java Buzz Posts
Latest Java Buzz Posts by Javin Paul
Latest Posts From Java67

Advertisement
One of the most common programming exercise for beginners is, write a program to check if given number is prime or not? There are many methods to check if a number is prime or not, but most common of them is trial division, which is what we will see in this tutorial. In my opinion these kind of program are their first steps towards algorithmic understanding. You first come with a solution, which is driven by fact that prime numbers are natural numbers, which are not divisible by any positive number other than 1 and themselves. You write a for loop to check every number, starting from 1 to given number, to see if given number is divisible by any positive number or not. This leads you to the solution. Then you find some more fact that there is no need to check till N-1, where N is the number we are checking for primeness, and checking till square root of N is enough. This reduces lot of time, especially while checking a large number is prime or not. Further, you come to know that if its not divisible by 2 then there is no need to checking for any other even number, and you increment counter by 2, instead of 1. So in a way, you learn how to optimize your solution by taking advantage of facts available. After this you can try something like Fibonacci series, or may be finding factorial of a number in Java to do some more practice on programming. This will not only teach you language basics e.g. loops, control statements like if-else, use of arithmetic and relational operator but also helps to develop programming logic.
Read more »

Read: How to Check if Given Number is Prime in Java - With Example

Topic: TextBox Example with JSF 2.0 Previous Topic   Next Topic Topic: IntelliJ IDEA 13.0.2 RC is Available

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use