Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
isqrt.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_ISQRT: {
28 Value v = pop_value(vm);
29 if (!((v.type == VAL_INT) || (v.type == VAL_FLOAT))) {
30 fprintf(stderr, "Runtime type error: ISQRT expects number, got %s\n", value_type_name(v.type));
31 exit(1);
32 }
33 int64_t a = (v.type == VAL_INT) ? v.i : (int64_t)v.d;
34 if (a <= 0) {
36 push_value(vm, make_int(0));
37 break;
38 }
39 /* Binary isqrt inline */
40 uint64_t n = (uint64_t)a;
41 uint64_t x = 0;
42 uint64_t bit = (uint64_t)1 << 62; /* highest even bit set */
43 while (bit > n)
44 bit >>= 2;
45 while (bit != 0) {
46 if (n >= x + bit) {
47 n -= x + bit;
48 x = (x >> 1) + bit;
49 } else {
50 x >>= 1;
51 }
52 bit >>= 2;
53 }
54 int64_t r = (int64_t)x;
57 break;
58}
Value a
Definition add.c:37
uint32_t r
Definition band.c:33
@ OP_ISQRT
Definition bytecode.h:270
Value v
Definition cast.c:22
Value x
Definition clamp.c:32
int n
Definition insert.c:41
uint64_t bit
Definition isqrt.c:42
push_value(vm, make_int(r))
free_value(v)
Tagged union representing a Fun value.
Definition value.h:68
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