I have an algorithm to compute a sequence of numbers (Collatz Conjecture) .
The problem is that I need all up to 1,000,000 (one million), from there I know which number creates the longest list, I can't think of good ideas but even if it were, I can't implement them in the code, so how can I know which is the list? longer?
If you can give me a serious helping hand, I just want some idea, so I can solve it, thank you.
This is my code:
public class Collatz14 {
public static void main(String[] args) {
}
public static void pruebaSecuencia(){
for (int i = 5; i < 1000000; i++) {
getSequence(i);
}
}
public static int getSequence(int num){
Vector secuencia = new Vector(10);
while(num != 1){ //Algoritmo para obtener la secuencia de numeros
if(num % 2 == 0){
num = num/2;
secuencia.add(num);
}
else if(num % 2 != 0){
num = (num * 3)+ 1;
secuencia.add(num);
}
}
return secuencia.size(); //Retorno el tamaño de la secuencia
}
}
Code
Explanation
I have modified your program a little 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 will return the number of numbers found in this sequence.You see? It only returns an integer variable, whose value is the number of sequences it will find for each
numero
.Second
We have created the function
iniciarEjercicio()
in which the limit up to which our program will run will be specified. And in turn contains the algorithm in charge of determining which has been the number that obtained more sequences .Example online!
Result
You can store the sizes of the vectors in a Map inside the function
pruebaSecuencia()
,Then you evaluate which is the largest.
Another alternative with the same code that you have, you can add two variables at the beginning and in the method
pruebaSecuencia()
you do the validation:Then you just print the variables