Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.HashSet;
- public class BruteForce {
- public static final long OVERFLOW_LIMIT = (Long.MAX_VALUE -1)/3;
- public static final Long[] KNOWN_ODD_CYCLE = {1L,5L,7L,17L,25L,37L,55L,41L,61L,91L}; // Known cycle base that are odd.
- public static final int MAX_K = 10000; // Max iteration we do of f before giving up and going to the next n.
- public static final int LOW_BOUND_N = 100; // Lower bound of search on n.
- public static final int UP_BOUND_N = 20000000; // Upper bound of search on n.
- public static void main(String[] args) {
- HashSet<TripleResult> result = new HashSet<>();
- final HashSet<Long> knownOddCycle = new HashSet<>(Arrays.asList(KNOWN_ODD_CYCLE));
- for ( int n = LOW_BOUND_N ; n < UP_BOUND_N ; ++n) {
- HashSet<Long> alreadySeen = new HashSet<>(); // Value we already met during iteration of f.
- long x = n;
- // Let's iterate !
- for ( int k = 0 ; k < MAX_K ; ++k ) {
- if ( alreadySeen.contains(x) ) { // We found a cycle.
- if (x % 2 == 0) // Even.
- break;
- if ( knownOddCycle.contains(x)) // Already known.
- break;
- System.out.println("Found a new odd cycle starting at x=" + x +
- " with starting value n="+n + " after k="+ k + " iterations");
- result.add(new TripleResult(x, n, k));
- }
- alreadySeen.add(x);
- try {
- x = f(x); // We iterate and we catch possible integer overflow.
- } catch (Exception e) {
- System.err.println("Overflow on n=" + n + ". Will go to next n directly. " + e);
- break;
- }
- }
- if ( n % 10000 == 0 )
- System.out.println("Still searching... n=" + n);
- }
- System.out.println("Finished !");
- System.out.println("New results : " + result);
- }
- public static long f(long x) throws Exception {
- if (x % 2 == 0)
- return x/2;
- if ( x > OVERFLOW_LIMIT ) { // We use 64 bits long integer. We may overflow so we must be careful.
- throw new Exception("Overflow on x = " + x);
- }
- return 3*x-1;
- }
- public static class TripleResult {
- public final long x;
- public final long n;
- public final long k;
- public TripleResult(long x, long n, long k) {
- this.x = x;
- this.n = n;
- this.k = k;
- }
- @Override
- public String toString() {
- return "TripleResult [x=" + x + ", n=" + n + ", k=" + k + "]";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment