Prime numbers - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# Prime numbers

Posts: 9Member
Woul someone please tell me how to obtain prime numbers between 1 and 100 using java.

• Posts: 16Member
: Woul someone please tell me how to obtain prime numbers between 1 and 100 using java.
:

import java.lang.Math;
class prime

{
public static void main(String args[])

{
for (int i = 2; i <= 100; i++)

{
boolean isprime=true;
if (i == 2) System.out.println(i);
if (i%2 == 0) continue;
for (int j= 3; j<=Math.sqrt(i); j++)
if (i%j == 0)

{
isprime=false;
break;
}
if(isprime)System.out.println(i);
}
}
}
• Posts: 1,621Member
[b][red]This message was edited by Manning at 2004-6-23 18:42:5[/red][/b][hr]
: : Woul someone please tell me how to obtain prime numbers between 1 and 100 using java.
: :
:
[code]
: import java.lang.Math;
: class prime
: {
: public static void main(String args[])
: {
: for (int i = 2; i <= 100; i++)
: {
: boolean isprime=true;
: if (i == 2) System.out.println(i);
: if (i%2 == 0) continue;
: for (int j= 3; j<=Math.sqrt(i); [red]j+=2[/red])
: {
: if (i%j == 0)
: {
: isprime=false;
: break;
: }
: }
: if(isprime)System.out.println(i);
: }
: }
: }
[/code]

Just thought I would throw in a nice easy tweak to improve the speed. Going from 1 to 100 you won't even notice the difference it makes, but with larger numbers that small change can give a huge improvement.

And of course there are ways to make it even faster, but they would require more than 2 characters to change

• Posts: 67Member