Factors of an integer: Difference between revisions

Odin version
(Added MSX Basic and Quite BASIC)
(Odin version)
Line 4,669:
List.filter (fun v -> (n mod v) = 0) (range n)</syntaxhighlight>
 
=={{header|Odin}}==
Uses built-in dynamic arrays, and only checks up to the square root
<syntaxhighlight lang="odin">
package main
 
import "core:fmt"
import "core:slice"
 
factors :: proc(n: int) -> [dynamic]int {
d := 1
factors := make([dynamic]int)
 
for {
q := n / d
r := n % d
 
if d >= q {
if d == q && r == 0 {
append(&factors, d)
}
slice.sort(factors[:])
return factors
}
if r == 0 {
append(&factors, d, q)
}
 
d += 1
}
}
 
main :: proc() {
for n in ([?]int{100, 108, 999, 255, 256, 257}) {
a := factors(n)
fmt.println("The factors of", n, "are", a)
delete(a)
}
}
</syntaxhighlight>
{{Out}}
<pre>
The factors of 100 are [1, 2, 4, 5, 10, 20, 25, 50, 100]
The factors of 108 are [1, 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, 108]
The factors of 999 are [1, 3, 9, 27, 37, 111, 333, 999]
The factors of 255 are [1, 3, 5, 15, 17, 51, 85, 255]
The factors of 256 are [1, 2, 4, 8, 16, 32, 64, 128, 256]
The factors of 257 are [1, 257]
</pre>
=={{header|Oforth}}==
 
357

edits