3. ทำซ้ำ ๆ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 3-15  โปรแกรมทดสอบความเป็นจำนวนเฉพาะ แบบวนรับจากผู้ใช้ได้หลายตัว
import java.util.Scanner;
// โปรแกรมทดสอบว่าจำนวนเต็มที่ได้รับเป็นจำนวนเฉพาะหรือไม่ 
public class Primality {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    while (true) { // วงวนรับจำนวนจากผู้ใช้ 
      System.out.print("n = ");
      int n = kb.nextInt();
      if (n <= 1) break;
      int k = 2;
      while (true) { // วงวนทดสอบจำนวนเฉพาะ 
        if (k >= n) break;
        if ((n % k) == 0) break;
        k++;
      }
      System.out.println(k == n);
    }
  }
}
©2009 S.Prasitjutrakul