簡體   English   中英

對於循環幫助,請檢查素數

[英]For Loop help, checking prime numbers

        for (int i = lo; i <= hi; i++)  
    {
        boolean isPrime = true;  // each value of i starts out assuming it IS prime
        // Write a loop below that divides i by 2,3,4,5 etc upto i/2 
        // If at any time you find a divisor that evenly divides i
        // Then set isPrime to false    

        /* your prime checking loop HERE */
        for (int j = 2; j <= hi / 2; j++)
        {
            if (i % j == 0)
            {
                isPrime = false;
            }
        }   
        // DO NOT REMOVE OR MODIFY LINE BELOW
        if ( isPrime )
            System.out.print( i + " " );
    }

好的,這是我當前擁有的代碼,我假設問題出在其中。 該程序獲取一個文本輸入文件,並將第一個值設置為lo(在我的文本演示中,lo = 3和hi =73。)不管出於什么原因,唯一輸出為'prime'的數字都始於41和然后完全沒問題 我不知道為什么前一半的數字根本沒有輸出。

請記住,我必須為此項目使用for循環,方法和此類方法目前不在“詞匯表”中。 試圖保持簡單。 我會很感謝幫助的人。

再次閱讀注釋塊。 它說循環直到i / 2。 您要循環播放直到hi / 2。

問題是您一直在使用數字的模數。

3%3是零,但3是質數。

在主要檢查循環中,選擇以下一項:

for (int j = 2; j < i / 2; j++)

要么

for (int j = 2; j <= sqrt(i); j++)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM