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
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
27
case
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) {
35
free_value
(
v
);
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
;
55
free_value
(
v
);
56
push_value
(vm,
make_int
(
r
));
57
break
;
58
}
a
Value a
Definition
add.c:37
r
uint32_t r
Definition
band.c:33
OP_ISQRT
@ OP_ISQRT
Definition
bytecode.h:270
v
Value v
Definition
cast.c:22
x
Value x
Definition
clamp.c:32
n
int n
Definition
insert.c:41
bit
uint64_t bit
Definition
isqrt.c:42
push_value
push_value(vm, make_int(r))
free_value
free_value(v)
Value
Tagged union representing a Fun value.
Definition
value.h:68
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