Diese Aufgabe möchte ich programmieren.
Hierzu habe ich folgenden Code erstellt.
[JAVA=42]public class Problem14 {
public static int folge2(int n){
int[]f=new int[n];
int i=1;
for(int n1=1; n1<=n; n1++){
int a=n1;
while(a!=1){
if(a%2==0){
a/=2;
i++;
}
else{
a=3*a+1;
i++;
}
if(a<n1){
i+=f[a-1]-1;
a=1;
}
}
f[n1-1]=i;
i=1;
}
int max=0;
int index=0;
for(int j=0; j<n; j++){
if(f[j]>max){
max=f[j];
index=j+1;
}
}
System.out.println("Die Zahl "+index+" produziert die laengste Kette von "+max);
return max;
}
public static void main(String[] args) {
long s=System.currentTimeMillis();
folge2(100000);
long f=System.currentTimeMillis();
long d=f-s;
System.out.println("Dauer: "+d);
}
}[/code]
Das Problem besteht darin dass in der Zeile 20, nämlich
eine outofbound-Exception kommt und ich nicht weiß wieso. Das passiert übrigens nicht, wenn ich statt 1 Million nur die Zahlen bis 100000 einbeziehe.
Es würde mich echt sehr freuen, wenn ihr mir helfen könntet.
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Hierzu habe ich folgenden Code erstellt.
[JAVA=42]public class Problem14 {
public static int folge2(int n){
int[]f=new int[n];
int i=1;
for(int n1=1; n1<=n; n1++){
int a=n1;
while(a!=1){
if(a%2==0){
a/=2;
i++;
}
else{
a=3*a+1;
i++;
}
if(a<n1){
i+=f[a-1]-1;
a=1;
}
}
f[n1-1]=i;
i=1;
}
int max=0;
int index=0;
for(int j=0; j<n; j++){
if(f[j]>max){
max=f[j];
index=j+1;
}
}
System.out.println("Die Zahl "+index+" produziert die laengste Kette von "+max);
return max;
}
public static void main(String[] args) {
long s=System.currentTimeMillis();
folge2(100000);
long f=System.currentTimeMillis();
long d=f-s;
System.out.println("Dauer: "+d);
}
}[/code]
Das Problem besteht darin dass in der Zeile 20, nämlich
Code:
i+=f[a-1]-1;
Es würde mich echt sehr freuen, wenn ihr mir helfen könntet.