Java prime numbers detector

Write a program that uses two nested for loops and the modulus operator (%) to detect and print prime numbers. A prime numbers are integral numbers that are not evenly divisible by any other numbers except themselves and 1. Use your program to print all the prime numbers from 0 to 10,000. Print 10 numbers per output line, separated by two spaces.- asked by Raj on our Facebook profile

package com.itcuties.questions;

public class Answer {
	public static void main(String[] args) {
		int found=0;
		for (int i=1; i<=10000; i++) {
			for (int j=1; j <= i; j++) {
				if (i % j == 0 && i != j && j != 1) {	// watch out for the j==1
					break;
				}
				if (i == j)
					if ((++found)%10 == 0)
						System.out.println(i);
					else
						System.out.print(i+"  ");
			}
		}
	}
}

2 Responses to "Java prime numbers detector"

  1. Matteo says:

    I’d like to propose 2 improvements on your code:

    1. Is there any sense in starting looping from j=1, and checking if j!=1 on the next line? :) Start looping i and j from 2, and you’ll get the same result without that condition (even if is very rarely evaluated).
    Same observation apply for checking if “i%j==0 && i!=j”. Just stop looping at “j<i"

    2. To state whether a number "a" is prime, you suggest to check if every number, save 1, lesser or equal than "a" can divide "a". And this is bad for computation time. My approach is creating an ArrayList of the prime numbers found, and when checking a number "n", check if any of the prime found and lesser than "(int)sqrt(n)+1" can divide "n". This can be proved to be equivalent to your solution, but runs extremely faster.

    Hope this is useful, keep doing such a great work girls!

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW