Problem 042

How many triangle words in data/p042.txt?

Answer162
Output162
StatusPASS
Native helperno
Runtime0 ms
Peak memory1104 KB
Time complexityO(n) (estimated)
Space complexityO(1) (estimated)

Performance comparison

MetricOur solutionBest known
Time complexityO(n)O(n log n)
Space complexityO(1)O(n)
ApproachFlow solutionSort + triangle number check
VerdictOptimal

Flow source

# Project Euler 042
# How many triangle words in data/p042.txt?

extern {
    function fopen(path: string, mode: string) -> ptr<void>
    function fgetc(f: ptr<void>) -> i32
    function fclose(f: ptr<void>) -> i32
}

function is_triangle(x: i64) -> bool {
    # n(n+1)/2 = x ⇒ 8x+1 perfect square and odd root
    let mut s: i64 = 1
    while s * s < 8 * x + 1 {
        s = s + 1
    }
    if s * s != 8 * x + 1 { return false }
    return (s - 1) % 2 == 0
}

function main() -> i32 {
    let f: ptr<void> = fopen("data/p042.txt", "r")
    if f == null {
        printf("failed to read data/p042.txt\n")
        return 1
    }
    let mut count: i64 = 0
    let mut score: i64 = 0
    let mut in_word: bool = false
    let mut c: i32 = fgetc(f)
    while c >= 0 {
        if c == 34 {
            if in_word {
                if is_triangle(score) {
                    count = count + 1
                }
                score = 0
                in_word = false
            } else {
                in_word = true
                score = 0
            }
        } elif in_word {
            if c >= 65 && c <= 90 {
                score = score + ((c - 64) as i64)
            }
        }
        c = fgetc(f)
    }
    fclose(f)
    printf("%lld\n", count)
    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; }

bool is_triangle_i64(int64_t x);
int32_t main(void);




bool is_triangle_i64(int64_t x) {
    int64_t s = 1;
    while ((s * s) < ((8 * x) + 1)) {
        s = (s + 1);
    }
    if ((s * s) != ((8 * x) + 1)) {
        return 0;
    }
    return FLOW_CHECKED_MOD(((s - 1)), (2)) == 0;
}

int32_t main(void) {
    void* f = (void*)(fopen("data/p042.txt", "r"));
    if (f == NULL) {
        printf("failed to read data/p042.txt\n");
        return 1;
    }
    int64_t count = 0;
    int64_t score = 0;
    bool in_word = 0;
    int32_t c = fgetc(f);
    while (c >= 0) {
        if (c == 34) {
            if (in_word) {
                if (is_triangle_i64(score)) {
                    count = (count + 1);
                }
                score = 0;
                in_word = 0;
            } else {
                in_word = 1;
                score = 0;
            }
        } else if (in_word) {
            if ((c >= 65 && c <= 90)) {
                score = (score + ((int64_t)((c - 64))));
            }
        }
        c = fgetc(f);
    }
    fclose(f);
    printf("%lld\n", count);
    return 0;
}

Generated MLIR

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