Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
lcm.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2026 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
26
27case OP_LCM: {
28 Value vb = pop_value(vm);
29 Value va = pop_value(vm);
30 if (!((va.type == VAL_INT) || (va.type == VAL_FLOAT)) ||
31 !((vb.type == VAL_INT) || (vb.type == VAL_FLOAT))) {
32 fprintf(stderr, "Runtime type error: LCM expects numbers, got %s and %s\n",
33 value_type_name(va.type), value_type_name(vb.type));
34 exit(1);
35 }
36 int64_t a = (va.type == VAL_INT) ? va.i : (int64_t)va.d;
37 int64_t b = (vb.type == VAL_INT) ? vb.i : (int64_t)vb.d;
38 if (a == INT64_MIN)
39 a = (int64_t)INT64_MAX;
40 else if (a < 0)
41 a = -a;
42 if (b == INT64_MIN)
43 b = (int64_t)INT64_MAX;
44 else if (b < 0)
45 b = -b;
46 if (a == 0 || b == 0) {
48 free_value(vb);
49 push_value(vm, make_int(0));
50 break;
51 }
52 /* gcd(a,b) */
53 int64_t x = a, y = b;
54 while (y != 0) {
55 int64_t t = x % y;
56 x = y;
57 y = t;
58 }
59 int64_t g = x;
60 /* lcm = (a/g)*b (attempt to reduce overflow) */
61 int64_t l = (a / g) * b;
66 break;
67}
Value a
Definition add.c:37
int res
Definition and.c:34
Value va
Definition band.c:30
uint32_t b
Definition band.c:32
@ OP_LCM
Definition bytecode.h:269
Value x
Definition clamp.c:32
int64_t y
Definition lcm.c:53
int64_t l
Definition lcm.c:61
free_value(va)
int64_t g
Definition lcm.c:59
push_value(vm, res)
long t
Definition sleep_ms.c:32
Tagged union representing a Fun value.
Definition value.h:68
int64_t i
Definition value.h:71
double d
Definition value.h:72
ValueType type
Definition value.h:69
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ VAL_INT
Definition value.h:51
@ VAL_FLOAT
Definition value.h:58
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230