Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
gcd.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_GCD: {
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: GCD 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 while (b != 0) {
47 int64_t t = a % b;
48 a = b;
49 b = t;
50 }
55 break;
56}
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_GCD
Definition bytecode.h:268
free_value(va)
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