Problem 014

Starting number under one million that produces the longest Collatz chain. Memoized in a heap buffer — Flow malloc → same C performance.

Answer837799
Output837799
StatusPASS
Native helperno
Runtime10 ms
Peak memory5024 KB
Time complexityO(n) (estimated)
Space complexityO(n) (estimated)

Performance comparison

MetricOur solutionBest known
Time complexityO(n)O(n)
Space complexityO(n)O(n)
ApproachFlow solutionMemoised Collatz lengths
VerdictOptimal

Flow source

# Project Euler 014
# Starting number under one million that produces the longest Collatz chain.
# Memoized in a heap buffer — Flow malloc → same C performance.

extern {
    function calloc(n: i64, size: i64) -> ptr<void>
    function free(p: ptr<void>) -> void
}

function collatz_len(n0: i64, memo: ptr<i32>, limit: i64) -> i32 {
    let mut n: i64 = n0
    let mut steps: i32 = 0
    while n != 1 {
        if n < limit && memo[n] != 0 {
            return steps + memo[n]
        }
        if n % 2 == 0 {
            n = n / 2
        } else {
            n = 3 * n + 1
        }
        steps = steps + 1
    }
    return steps + 1
}

function solve(limit: i64) -> i64 {
    let memo: ptr<i32> = calloc(limit, 4)
    if memo == null {
        return -1
    }
    memo[1] = 1

    let mut best_n: i64 = 1
    let mut best_len: i32 = 1
    for n in 2..limit {
        let len: i32 = collatz_len(n, memo, limit)
        memo[n] = len
        if len > best_len {
            best_len = len
            best_n = n
        }
    }
    free(memo)
    return best_n
}

function main() -> i32 {
    printf("%lld\n", solve(1000000))
    return 0
}

Generated C

#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Flow runtime helpers */
typedef struct flow_temp_node { struct flow_temp_node* next; } flow_temp_node;
static flow_temp_node* flow_temp_head = NULL;
static int flow_temp_atexit_set = 0;
__attribute__((unused)) static void flow_temp_free_all(void) {
    while (flow_temp_head) {
        flow_temp_node* n = flow_temp_head;
        flow_temp_head = n->next;
        free(n);
    }
}
__attribute__((unused)) static void* flow_temp_alloc(size_t nbytes) {
    flow_temp_node* node = (flow_temp_node*)malloc(sizeof(flow_temp_node) + nbytes);
    if (!node) return NULL;
    node->next = flow_temp_head;
    flow_temp_head = node;
    if (!flow_temp_atexit_set) {
        flow_temp_atexit_set = 1;
        atexit(flow_temp_free_all);
    }
    return (void*)(node + 1);
}
#ifndef FLOW_DIAG
#define FLOW_DIAG(msg) fprintf(stderr, "%s", (msg))
#endif
#ifndef FLOW_LOG
#define FLOW_LOG(fmt, ...) printf(fmt, __VA_ARGS__)
#endif
#ifndef FLOW_LOG_EMPTY
#define FLOW_LOG_EMPTY(fmt) printf(fmt)
#endif
static char* flow_strcat(const char* a, const char* b) {
    size_t la = strlen(a ? a : ""), lb = strlen(b ? b : "");
    char* r = (char*)flow_temp_alloc(la + lb + 1);
    if (!r) return NULL;
    if (la) memcpy(r, a, la);
    if (lb) memcpy(r + la, b, lb);
    r[la + lb] = '\0';
    return r;
}

#define __flow_in_arr(arr, val) __extension__ ({ \
    int _found = 0; \
    size_t _n = sizeof(arr)/sizeof((arr)[0]); \
    for (size_t _i = 0; _i < _n; _i++) { \
        if ((arr)[_i] == (val)) { _found = 1; break; } \
    } _found; })

/* Unified fault handler (MISRA #279) — override with -DFLOW_FAULT_HANDLER=fn */
#ifndef FLOW_FAULT_HANDLER
__attribute__((unused)) static inline void flow_fault_handler(const char* msg) {
    fprintf(stderr, "flow: %s\n", msg ? msg : "fault");
    abort();
#if defined(__GNUC__) || defined(__clang__)
    __builtin_unreachable();
#endif
}
#else
#define flow_fault_handler FLOW_FAULT_HANDLER
#endif
#define flow_div_by_zero_handler() flow_fault_handler("division by zero")
#define flow_shift_ub_handler() flow_fault_handler("invalid shift (amount out of range or left-shift of negative)")

#ifndef FLOW_CHECKED_DIV
#define FLOW_CHECKED_DIV(L, R) (((R) != 0) ? ((L) / (R)) : (flow_div_by_zero_handler(), (L) * 0))
#endif
#ifndef FLOW_CHECKED_MOD
#define FLOW_CHECKED_MOD(L, R) (((R) != 0) ? ((L) % (R)) : (flow_div_by_zero_handler(), (L) * 0))
#endif
#ifndef FLOW_CHECKED_SHL
#define FLOW_CHECKED_SHL(L, R) ((((R) >= 0) && ((unsigned long long)(R) < (sizeof(L) * 8ull)) && ((L) >= 0)) ? ((L) << (R)) : (flow_shift_ub_handler(), (L) * 0))
#endif
#ifndef FLOW_CHECKED_SHR
#define FLOW_CHECKED_SHR(L, R) ((((R) >= 0) && ((unsigned long long)(R) < (sizeof(L) * 8ull))) ? ((L) >> (R)) : (flow_shift_ub_handler(), (L) * 0))
#endif

#include <math.h>

void* _ui_state = NULL;

static inline float i32_to_f32(int32_t v) { return (float)v; }

/* Host stub for @gpu kernels (device codegen replaces this). */
static inline int32_t gpu_thread_id(void) { return 0; }

int32_t collatz_len_i64_ptr_i32_i64(int64_t n0, int32_t* memo, int64_t limit);
int64_t solve_i64(int64_t limit);
int32_t main(void);



int32_t collatz_len_i64_ptr_i32_i64(int64_t n0, int32_t* memo, int64_t limit) {
    int64_t n = n0;
    int32_t steps = 0;
    while (n != 1) {
        if ((n < limit && memo[n] != 0)) {
            return (steps + memo[n]);
        }
        if (FLOW_CHECKED_MOD((n), (2)) == 0) {
            n = FLOW_CHECKED_DIV((n), (2));
        } else {
            n = ((3 * n) + 1);
        }
        steps = (steps + 1);
    }
    return (steps + 1);
}

int64_t solve_i64(int64_t limit) {
    int32_t* memo = (int32_t*)(calloc(limit, 4));
    if (memo == NULL) {
        return (-1);
    }
    memo[1] = 1;
    int64_t best_n = 1;
    int32_t best_len = 1;
    int32_t __flow_step_1 = 1;
    for (int32_t n = 2; (2 <= limit) ? n < limit : n > limit; n += (2 <= limit) ? 1 : -1) {
        int32_t len = collatz_len_i64_ptr_i32_i64(n, memo, limit);
        memo[n] = len;
        if (len > best_len) {
            best_len = len;
            best_n = n;
        }
    }
    free(memo);
    return best_n;
}

int32_t main(void) {
    printf("%lld\n", solve_i64(1000000));
    return 0;
}

Generated MLIR

module {
  llvm.func @printf(!llvm.ptr, ...) -> i32
  llvm.mlir.global internal constant @str_0("%lld\n\00") {addr_space = 0 : i32} : !llvm.array<6 x i8>
  func.func private @calloc(i64, i64) -> !llvm.ptr
  func.func private @free(!llvm.ptr) -> ()
  func.func @collatz_len(%arg0: i64, %arg1: !llvm.ptr, %arg2: i64) -> i32 {
    %0 = llvm.mlir.constant(1 : i64) : i64
    %1 = llvm.alloca %0 x i64 : (i64) -> !llvm.ptr
    llvm.store %arg0, %1 : i64, !llvm.ptr
    %2 = arith.constant 0 : i32
    %3 = llvm.mlir.constant(1 : i64) : i64
    %4 = llvm.alloca %3 x i32 : (i64) -> !llvm.ptr
    llvm.store %2, %4 : i32, !llvm.ptr
    cf.br ^bb0
    ^bb0:
    %5 = llvm.load %1 : !llvm.ptr -> i64
    %6 = arith.constant 1 : i32
    %8 = arith.extsi %6 : i32 to i64
    %7 = arith.cmpi ne, %5, %8 : i64
    cf.cond_br %7, ^bb1, ^bb2
    ^bb1:
      %9 = llvm.load %1 : !llvm.ptr -> i64
      %10 = arith.cmpi slt, %9, %arg2 : i64
      %11 = scf.if %10 -> (i1) {
        %13 = llvm.load %1 : !llvm.ptr -> i64
        %14 = llvm.getelementptr %arg1[%13] : (!llvm.ptr, i64) -> !llvm.ptr, i32
        %12 = llvm.load %14 : !llvm.ptr -> i32
        %15 = arith.constant 0 : i32
        %16 = arith.cmpi ne, %12, %15 : i32
        scf.yield %16 : i1
      } else {
        %17 = arith.constant false
        scf.yield %17 : i1
      }
      cf.cond_br %11, ^bb3, ^bb4
      ^bb3:
        %18 = llvm.load %4 : !llvm.ptr -> i32
        %20 = llvm.load %1 : !llvm.ptr -> i64
        %21 = llvm.getelementptr %arg1[%20] : (!llvm.ptr, i64) -> !llvm.ptr, i32
        %19 = llvm.load %21 : !llvm.ptr -> i32
        %22 = arith.addi %18, %19 : i32
        func.return %22 : i32
      ^bb4:
        cf.br ^bb5
      ^bb5:
      %23 = llvm.load %1 : !llvm.ptr -> i64
      %24 = arith.constant 2 : i32
      %26 = arith.extsi %24 : i32 to i64
      %25 = arith.remsi %23, %26 : i64
      %27 = arith.constant 0 : i32
      %29 = arith.extsi %27 : i32 to i64
      %28 = arith.cmpi eq, %25, %29 : i64
      cf.cond_br %28, ^bb6, ^bb7
      ^bb6:
        %30 = llvm.load %1 : !llvm.ptr -> i64
        %31 = arith.constant 2 : i32
        %33 = arith.extsi %31 : i32 to i64
        %32 = arith.divsi %30, %33 : i64
        llvm.store %32, %1 : i64, !llvm.ptr
        cf.br ^bb8
      ^bb7:
        %34 = arith.constant 3 : i32
        %35 = llvm.load %1 : !llvm.ptr -> i64
        %37 = arith.extsi %34 : i32 to i64
        %36 = arith.muli %37, %35 : i64
        %38 = arith.constant 1 : i32
        %40 = arith.extsi %38 : i32 to i64
        %39 = arith.addi %36, %40 : i64
        llvm.store %39, %1 : i64, !llvm.ptr
        cf.br ^bb8
      ^bb8:
      %41 = llvm.load %4 : !llvm.ptr -> i32
      %42 = arith.constant 1 : i32
      %43 = arith.addi %41, %42 : i32
      llvm.store %43, %4 : i32, !llvm.ptr
      cf.br ^bb0
    ^bb2:
    %44 = llvm.load %4 : !llvm.ptr -> i32
    %45 = arith.constant 1 : i32
    %46 = arith.addi %44, %45 : i32
    func.return %46 : i32
  }
  func.func @solve(%arg0: i64) -> i64 {
    %48 = arith.constant 4 : i32
    %49 = arith.extsi %48 : i32 to i64
    %47 = func.call @calloc(%arg0, %49) : (i64, i64) -> !llvm.ptr
    %50 = llvm.mlir.zero : !llvm.ptr
    %51 = llvm.icmp "eq" %47, %50 : !llvm.ptr
    cf.cond_br %51, ^bb9, ^bb10
    ^bb9:
      %52 = arith.constant 1 : i32
      %54 = arith.constant 0 : i32
      %53 = arith.subi %54, %52 : i32
      %55 = arith.extsi %53 : i32 to i64
      func.return %55 : i64
    ^bb10:
      cf.br ^bb11
    ^bb11:
    %56 = arith.constant 1 : i32
    %57 = arith.constant 1 : i32
    %58 = arith.extsi %57 : i32 to i64
    %59 = llvm.getelementptr %47[%58] : (!llvm.ptr, i64) -> !llvm.ptr, i32
    llvm.store %56, %59 : i32, !llvm.ptr
    %60 = arith.constant 1 : i32
    %61 = arith.extsi %60 : i32 to i64
    %62 = llvm.mlir.constant(1 : i64) : i64
    %63 = llvm.alloca %62 x i64 : (i64) -> !llvm.ptr
    llvm.store %61, %63 : i64, !llvm.ptr
    %64 = arith.constant 1 : i32
    %65 = llvm.mlir.constant(1 : i64) : i64
    %66 = llvm.alloca %65 x i32 : (i64) -> !llvm.ptr
    llvm.store %64, %66 : i32, !llvm.ptr
    %67 = arith.constant 2 : i32
    %68 = arith.index_cast %67 : i32 to index
    %69 = arith.index_cast %arg0 : i32 to index
    %71 = arith.constant 1 : index
    %72 = arith.constant -1 : index
    %73 = arith.cmpi sle, %68, %69 : index
    %70 = arith.select %73, %71, %72 : index
    cf.br ^bb12(%68 : index)
    ^bb12(%74: index):
    %75 = arith.cmpi slt, %74, %69 : index
    %76 = arith.cmpi sgt, %74, %69 : index
    %77 = arith.select %73, %75, %76 : i1
    cf.cond_br %77, ^bb13(%74 : index), ^bb14(%74 : index)
    ^bb13(%78: index):
      %80 = arith.index_cast %78 : index to i64
      %79 = func.call @collatz_len(%80, %47, %arg0) : (i64, !llvm.ptr, i64) -> i32
      %81 = arith.index_cast %78 : index to i64
      %82 = llvm.getelementptr %47[%81] : (!llvm.ptr, i64) -> !llvm.ptr, i32
      llvm.store %79, %82 : i32, !llvm.ptr
      %83 = llvm.load %66 : !llvm.ptr -> i32
      %84 = arith.cmpi sgt, %79, %83 : i32
      cf.cond_br %84, ^bb15, ^bb16
      ^bb15:
        llvm.store %79, %66 : i32, !llvm.ptr
        %85 = arith.index_cast %78 : index to i64
        llvm.store %85, %63 : i64, !llvm.ptr
        cf.br ^bb17
      ^bb16:
        cf.br ^bb17
      ^bb17:
      %86 = arith.addi %78, %70 : index
      cf.br ^bb12(%86 : index)
    ^bb14(%87: index):
    func.call @free(%47) : (!llvm.ptr) -> ()
    %89 = llvm.load %63 : !llvm.ptr -> i64
    func.return %89 : i64
  }
  func.func @main() -> i32 {
    %90 = llvm.mlir.addressof @str_0 : !llvm.ptr
    %92 = arith.constant 1000000 : i32
    %93 = arith.extsi %92 : i32 to i64
    %91 = func.call @solve(%93) : (i64) -> i64
    %94 = llvm.call @printf(%90, %91) vararg(!llvm.func<i32 (ptr, ...)>) : (!llvm.ptr, i64) -> i32
    %95 = arith.constant 0 : i32
    func.return %95 : i32
  }
}