簡體   English   中英

初學者。 有人可以教我如何計算內部循環被執行的次數嗎?

[英]Beginner. Can someone teach me how to count the number of times the inner loop has been excecuted?

有人可以教我如何計算內部循環執行的次數嗎?

import java.util.*;
public class Lab8Ex5{
    public static void main(String[] args){
        int primeCount = 1;
        System.out.print(2);
        int num = 2;
        while (primeCount < 20){
            num++; // try next number
            boolean isPrime = true;
            for (int i = 2; i < num; i++){
                if(num%i==0) // divisible by i
                    isPrime = false; // not a prime
            }

            if (isPrime){
                primeCount++; // one more prime is found
                System.out.print(","+num);
            }
        }
        System.out.println("Done");
    }
}

計數的數量應該是 2415。我知道int count = 0; 對於 (...) 計數++; 可用於。 但是,我不知道我應該把它放在哪里。

您需要在循環之外定義一個計數器。

然后你需要增加嵌套循環內的計數器。

它將計算嵌套循環在外循環上的執行次數。

import java.util.*;
public class Lab8Ex5{
    public static void main(String[] args){
        int primeCount = 1;
        System.out.print(2);
        int num = 2;
        int counter = 0;   // Define the counter and init it
        while (primeCount < 20){
            num++; // try next number
            boolean isPrime = true;
            for (int i = 2; i < num; i++){
                counter++;     // Increment the counter in the inner loop
                if(num%i==0) // divisible by i
                    isPrime = false; // not a prime
            }

            if (isPrime){
                primeCount++; // one more prime is found
                System.out.print(","+num);
            }
        }
        // Print the value of counter
        System.out.println("Done in " + counter + " steps");
    }
}

暫無
暫無

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

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