Fun
0.41.5
The programming language that makes You have fun
Main Page
Data Structures
Files
File List
Globals
Loading...
Searching...
No Matches
src
vm
math
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
27
case
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) {
47
free_value
(
va
);
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
;
62
Value
res
=
make_int
(
l
);
63
free_value
(
va
);
64
free_value
(vb);
65
push_value
(vm,
res
);
66
break
;
67
}
a
Value a
Definition
add.c:37
res
int res
Definition
and.c:34
va
Value va
Definition
band.c:30
b
uint32_t b
Definition
band.c:32
OP_LCM
@ OP_LCM
Definition
bytecode.h:269
x
Value x
Definition
clamp.c:32
y
int64_t y
Definition
lcm.c:53
l
int64_t l
Definition
lcm.c:61
free_value
free_value(va)
g
int64_t g
Definition
lcm.c:59
push_value
push_value(vm, res)
t
long t
Definition
sleep_ms.c:32
Value
Tagged union representing a Fun value.
Definition
value.h:68
Value::i
int64_t i
Definition
value.h:71
Value::d
double d
Definition
value.h:72
Value::type
ValueType type
Definition
value.h:69
make_int
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition
value.c:51
VAL_INT
@ VAL_INT
Definition
value.h:51
VAL_FLOAT
@ VAL_FLOAT
Definition
value.h:58
fprintf
#define fprintf
Definition
vm.c:200
exit
#define exit(code)
Definition
vm.c:230
Generated on
for Fun by
1.16.1