for循环
//for循环就像一个计数器,重复执行循环体
//for(初始化;条件;单步动作),举例如下
//for循环总是能用while循环替换,反之亦然
for (i=0;i<5;i=i+1)
{
//函数体
}
利用for循环判断小于n范围内的数字是否为素数的程序如下,这里面用到break函数跳出当前循环。
package hello;
import java.util.Scanner;
public class Hello {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
int n = in.nextInt();
int isPrime = 1;
for (int i = 2; i<n; i++)
{
if (n % i == 0)
{
isPrime = 0;
//System.out.println(n+"不是素数");
break;
}
}
if (isPrime == 1)
{
System.out.println(n+"是素数");
}
else
{
System.out.println(n+"不是素数");
}
}
}
如何写出100以内的素数?
package hello;
import java.util.Scanner;
public class Hello {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
//int n = in.nextInt();
for (int n = 2; n<100; n++)
{
int isPrime = 1;
for (int i = 2; i<n; i++)
{
if (n % i == 0)
{
isPrime = 0;
//System.out.println(n+"不是素数");
break;
}
}
if (isPrime == 1)
{
System.out.println(n+"是素数");
}
else
{
System.out.println(n+"不是素数");
}
}
}
}
输出前50个素数的程序传统方法如下:
package hello;
import java.util.Scanner;
public class Hello {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
int[] prime = new int[50];
prime[0] = 2;
int cnt = 1;
MAIN_LOOP:
for (int x = 3; cnt<50; x++)
{
for (int i = 0; i<cnt; i++)
{
if (x % prime[i] ==0)
{
continue MAIN_LOOP;
}
}
prime[cnt++] = x;
}
for (int k:prime)
{
System.out.print(k+" ");
}
}
}
输出100以内的素数的另外一种程序如下:
package hello;
import java.util.Scanner;
public class Hello {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
boolean[] isPrime = new boolean[100];
for (int i=2; i<isPrime.length; i++)
{
isPrime[i] = true;
}
for (int i=2; i<isPrime.length; i++)
{
if (isPrime[i])
{
for (int k=2; i*k<isPrime.length; k++)
{
isPrime[i*k] = false;
}
}
}
for (int i=0; i<isPrime.length; i++)
{
if (isPrime[i])
{
System.out.print(i+" ");
}
}
}
}