Skip to content

Instantly share code, notes, and snippets.

@Beritra
Last active March 22, 2020 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Beritra/50bf0d149f83885fa4e3bb89f54c1f76 to your computer and use it in GitHub Desktop.
Save Beritra/50bf0d149f83885fa4e3bb89f54c1f76 to your computer and use it in GitHub Desktop.
考拉兹猜想 Collatz conjecture
public class CollatzConjecture {
AtomicInteger max = new AtomicInteger(0);
int[] ints = new int[100000001];
public static void main(String[] args) {
CollatzConjecture test = new CollatzConjecture();
long timestamp = System.currentTimeMillis();
System.out.println(test.count());
System.out.println(System.currentTimeMillis() - timestamp);
}
int count() {
CountDownLatch countLatchTest = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
int finalI = i;
new Thread(() -> {
for (int j = 0; j < 10000000; j++) {
if (j % 1000000 == 0)
System.out.println(j);
int num = j * 10 + finalI;
max.compareAndSet(max.get(), Math.max(collatz(num), max.get()));
}
countLatchTest.countDown();
}).start();
}
try {
countLatchTest.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return max.get();
}
int collatz(long n) {
int index = 1;
final long x = n;
while (n > 1) {
if (n < 100000000 && ints[(int) n] != 0) {
index += ints[(int) n] - 1;
break;
}
if (n % 2 == 0) {
n = n / 2;
} else {
n = n * 3 + 1;
}
index++;
}
if (ints[(int) x] == 0)
ints[(int) x] = index;
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment