Code
public class Main {
public static void iniciarEjercicio(int limite) {
/* Secuencia Mayor */
int numeroMayor = 0;
int cantidadSecuenciaMayor = 0;
for (int i = 5; i < limite; i++) {
int cantidadSecuencia = obtenerSecuencia(i);
if (cantidadSecuencia > cantidadSecuenciaMayor) {
numeroMayor = i;
cantidadSecuenciaMayor = cantidadSecuencia;
}
}
System.out.println("El numero que genera mas secuencia es el " + numeroMayor + " con " + cantidadSecuenciaMayor + " secuencias.");
}
public static int obtenerSecuencia(int numero) {
int contador = 0;
while (numero != 1) {
contador++;
if (numero / 2.0 == numero / 2) {
numero /= 2;
} else {
numero = (3 * numero + 1) / 2;
}
}
return contador;
}
public static void main(String[] args) {
/* Iniciamos el Programa */
iniciarEjercicio(1000000);
}
}
Explanation
I have modified your program a bit to make it a little easier, it is not necessary to use arrangements or anything like that, I will explain it to you part by part.
First
We have created the function start obtenerSecuencia()
, which receives a number as a parameter and returns the number of numbers found in this sequence.
public static int obtenerSecuencia(int numero) {
int contador = 0;
while (numero != 1) {
contador++;
if (numero / 2.0 == numero / 2) {
numero /= 2;
} else {
numero = (3 * numero + 1) / 2;
}
}
return contador;
}
See? It only returns an integer variable, whose value is the number of sequences you will find for each numero
.
Second
We have created the function iniciarEjercicio()
in which the limit to which our program will run will be specified. And in turn contains the algorithm responsible for determining which has been the number that obtained more sequences .
public static void iniciarEjercicio(int limite) {
/* Secuencia Mayor */
int numeroMayor = 0;
int cantidadSecuenciaMayor = 0;
for (int i = 5; i < limite; i++) {
int cantidadSecuencia = obtenerSecuencia(i);
if (cantidadSecuencia > cantidadSecuenciaMayor) {
numeroMayor = i;
cantidadSecuenciaMayor = cantidadSecuencia;
}
}
System.out.println("El numero que genera mas secuencia es el " + numeroMayor + " con " + cantidadSecuenciaMayor + " secuencias.");
}
Note: The online example runs only up to the number 1000, because if you run up to 1 million, it generates slowness in the compiler.
Result
The number that generates the most sequence is 871 with 113 sequences.