第一题可以用 Eratosthenes 演算法来求!
复制程式
import java.util.*;
public class Prime
{
public static int[] findPrimes(final int max)
{
int[] prime = new int[max+1];
ArrayList list = new ArrayList();
for(int i = 2; i <= max; i++)
{prime[i] = 1;}
for(int i = 2; i*i <= max; i++)
{
if(prime[i] == 1)
{
for(int j = 2*i; j <= max; j++)
{
if(j % i == 0)
{prime[j] = 0;}
}
}
}
for(int i = 2; i < max; i++)
{
if(prime[i] == 1)
{list.add(new Integer(i));}
}
int[] p = new int[list.size()];
Object[] objs = list.toArray();
for(int i = 0; i < p.length; i++)
{p[i] = ((Integer) objs[i]).intValue();}
return p;
}
public static void main(String[] args)
{
int[] prime = Prime.findPrimes(50); // 改这里, 若想求到1000之内, 就写1000, 要求到50之内就写50!
for(int i = 0; i < prime.length; i++)
{System.out.print(prime[i] + " ");}
System.out.println();
}
}