2017-06-13 50 views
1

一般問題:我會在註釋的哪裏放置for循環?將範圍內的所有素數加到數組中

深入問題:在Android Dev Studio的程序中,我設置了基本的「Hello World」程序(在文本框中鍵入消息,單擊「發送」按鈕,消息出現在下一個活動中)。

但是,我想將該程序調整爲一個人可以在文本框中鍵入數字的程序,程序將找到1和輸入數字之間的所有素數。

以下是我的代碼到目前爲止,與語法部分的評論我不知道如何格式化。

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.

有沒有辦法讓在輸入其餘條款之前設置數組的一部分?如果沒有,有沒有一種方法可以編輯程序,以便這些數字看起來像素數?

回答

1

此代碼應幫助您:

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); 
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++); 
} 
相關問題