Eratosthenes(寻找者)

时间:2014-10-30 16:23:04

标签: java arrays methods bluej

该计划的目标是找到低于某个最大值的素数。 cancelNonPrimes()方法的作用就像它在工作(在逐步调试器中)但只是不会将错误值写入列表......

public class Era2
{
    int m;
    int i;
    boolean[] list;
   /**
    * Constructor for objects of class Era2
    */
   public Era2(int max) {
     m = max;
     list = new boolean[m];
     initialize();
   }

   /**
    * Constructor for objects of class Era2 with standard-maximum-value = 25
    */
   public Era2() {
     m = 25;
     list = new boolean[m];
     initialize();
   }

   /**
    * Method for initializing an object: all values to true except 0 and 1
    */
   void initialize() {
       while (i < m) {
            setList(i, true);
            i = i + 1;
       }
       setList(0, false);
       setList(1, false);
   }

   /**
    * Method for setting a bool to a number on the list
    */
   void setList(int p, boolean b) {
        list[p] = b;
   }

   /**
    * Method for reading the entire list, printed in terminal
    */
   void getList() {
        for (int p = 0; p < m; p++){
         if (readList(p) == true){
            System.out.println(p + "true");
        }
        else {
            System.out.println(p + "false");
        }
        }
   }

   /**
    * Method for reading a specific shizl on the list
    */
   boolean readList(int p) {
    return list[p];
    }

   /**
    * Method for setting all non-primes to false
    */
   void cancelNonPrimes() {
    i = 2;
       while (i < m) {
       if (readList(i) == true) {
         int c = i;
         int n = 2;
         while (c < m) {
           c = (i * n);
           setList(c, false);
           n = n + 1;
         }
       }
      i = i + 1;
    }
   }
}

0 个答案:

没有答案