Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

79
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda