Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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");
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda