Added prime numbers example
This commit is contained in:
parent
c8045cb4fb
commit
3e3567cd32
47
examples/prime/prime.q
Normal file
47
examples/prime/prime.q
Normal file
@ -0,0 +1,47 @@
|
||||
import log
|
||||
import sys
|
||||
|
||||
main() {
|
||||
n := 100
|
||||
i := 2
|
||||
|
||||
loop {
|
||||
if i > n {
|
||||
return
|
||||
}
|
||||
|
||||
if isPrime(i) == 1 {
|
||||
if i != 2 {
|
||||
sys.write(1, " ", 1)
|
||||
}
|
||||
|
||||
log.number(i)
|
||||
}
|
||||
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
|
||||
isPrime(x) {
|
||||
if x == 2 {
|
||||
return 1
|
||||
}
|
||||
|
||||
if x % 2 == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
i := 3
|
||||
|
||||
loop {
|
||||
if i * i > x {
|
||||
return 1
|
||||
}
|
||||
|
||||
if x % i == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
i += 2
|
||||
}
|
||||
}
|
@ -1,6 +1,7 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"git.akyoto.dev/cli/q/src/build/arch/x64"
|
||||
"git.akyoto.dev/cli/q/src/build/asm"
|
||||
"git.akyoto.dev/cli/q/src/build/cpu"
|
||||
"git.akyoto.dev/cli/q/src/build/errors"
|
||||
@ -24,12 +25,16 @@ func (f *Function) ExecuteRegisterNumber(operation token.Token, register cpu.Reg
|
||||
f.RegisterNumber(asm.MUL, register, number)
|
||||
|
||||
case token.Div, token.DivAssign:
|
||||
f.SaveRegister(x64.RAX)
|
||||
f.SaveRegister(x64.RDX)
|
||||
tmp := f.NewRegister()
|
||||
f.RegisterNumber(asm.MOVE, tmp, number)
|
||||
f.RegisterRegister(asm.DIV, register, tmp)
|
||||
f.FreeRegister(tmp)
|
||||
|
||||
case token.Mod, token.ModAssign:
|
||||
f.SaveRegister(x64.RAX)
|
||||
f.SaveRegister(x64.RDX)
|
||||
tmp := f.NewRegister()
|
||||
f.RegisterNumber(asm.MOVE, tmp, number)
|
||||
f.RegisterRegister(asm.MODULO, register, tmp)
|
||||
|
@ -1,6 +1,7 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"git.akyoto.dev/cli/q/src/build/arch/x64"
|
||||
"git.akyoto.dev/cli/q/src/build/asm"
|
||||
"git.akyoto.dev/cli/q/src/build/cpu"
|
||||
"git.akyoto.dev/cli/q/src/build/errors"
|
||||
@ -24,9 +25,13 @@ func (f *Function) ExecuteRegisterRegister(operation token.Token, register cpu.R
|
||||
f.RegisterRegister(asm.MUL, register, operand)
|
||||
|
||||
case token.Div, token.DivAssign:
|
||||
f.SaveRegister(x64.RAX)
|
||||
f.SaveRegister(x64.RDX)
|
||||
f.RegisterRegister(asm.DIV, register, operand)
|
||||
|
||||
case token.Mod, token.ModAssign:
|
||||
f.SaveRegister(x64.RAX)
|
||||
f.SaveRegister(x64.RDX)
|
||||
f.RegisterRegister(asm.MODULO, register, operand)
|
||||
|
||||
case token.And, token.AndAssign:
|
||||
|
@ -24,6 +24,7 @@ var examples = []struct {
|
||||
{"itoa", "", "9223372036854775807", 0},
|
||||
{"collatz", "", "6 3 10 5 16 8 4 2 1", 0},
|
||||
{"fizzbuzz", "", "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz", 0},
|
||||
{"prime", "", "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97", 0},
|
||||
}
|
||||
|
||||
func TestExamples(t *testing.T) {
|
||||
|
Loading…
Reference in New Issue
Block a user