【问题标题】:Add all prime numbers in a range to an array将范围内的所有素数添加到数组中
【发布时间】:2017-11-15 18:18:57
【问题描述】:

一般问题:我会将 cmets 放在我的 for 循环中的什么位置?

深入问题:在 Android Dev Studio 上的一个程序中,我设置了基本的“Hello World”程序(在文本框中输入一条消息,单击“发送”按钮,该消息出现在下一个活动中) .

但是,我想将该程序改编为一个人可以在文本框中输入一个数字的程序,该程序将找到 1 和输入的数字之间的所有素数。

以下是我目前为止的代码,cmets 在语法我不知道如何格式化的部分。

public class Main2Activity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    int limit = Integer.parseInt(message);
    int a[limit];
    for(int i = 1; i <= limit; i++)
    {
        if(i%2 = 0 || i%3 = 0 || i%5 = 0 || i%7 = 0)
        { 
            //I want the program to move on to the next number
        }
        else
        {
            //I want this number to be added into the array
        }
    }

    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(a);
    //a being the name of the array created

我遇到的另一个问题是 程序不会将 1、2、3、5 和 7 识别为素数,因为它们被自己除,因此有余数为 0。

有没有办法在输入其余条款之前设置部分数组?如果没有,有没有办法我可以编辑程序以便显示这些数字作为素数?

【问题讨论】:

    标签: java android arrays for-loop


    【解决方案1】:

    最好使用完善的 API 来查找素数,例如 org.apache.commons.math3.primes.Primes。它为您提供了一个方法nextPrime(int n),您可以在示例中像这样使用它:

    ArrayList<Integer> a = new ArrayList<Integer>(limit);
    
    for(int i = 1; i <= limit; i = Primes.nextPrime(i))
    {
        a.add(i++);  
    }
    

    【讨论】:

      【解决方案2】:

      此代码应该可以帮助您:

          String primeNumbers = "";
          for (int i = 1, num = 0; i <= limit; i++) {
              int counter = 0;
              for (num = i; num >= 1; num--) {
                  if (i % num == 0) {
                      counter = counter + 1;
                  }
              }
              if (counter == 2) {
      
                  primeNumbers += i + " ";
              }
          }
      
          TextView textView = (TextView) findViewById(R.id.textView);
          textView.setText(primeNumbers);
      

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 2018-05-23
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多