Dave LAU
Dave LAU

Reputation: 41

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

Can someone teach me how to count the number of times the inner loop has been executed?

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");
    }
}

The number of counts should be 2415. I know that int count = 0; for (...) count++ ; could be used. However, I don't know where should I put that on.

Upvotes: 4

Views: 57

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26956

You need to define a counter outside the loops.

Then you need to increment the counter inside the nested loop.

It will count the number of executions of the nested loop over the outer loop.

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");
    }
}

Upvotes: 1

Related Questions