5 changed files with 92 additions and 21 deletions
@ -0,0 +1,36 @@ |
|||
package main |
|||
|
|||
// Go version of a prime number finder |
|||
|
|||
import ( |
|||
"fmt" |
|||
"math" |
|||
"os" |
|||
"strconv" |
|||
) |
|||
|
|||
// In stead of in place printing of each prime, it seems |
|||
// fmt.Println is costly, and causes the program to take |
|||
// 7x more time, so we gain speed at the expense of RAM |
|||
// by storing them all in a slice and printing once |
|||
func main() { |
|||
if len(os.Args) < 2 { |
|||
fmt.Println("Usage: go run primes.go [MAX]") |
|||
return |
|||
} |
|||
primes := make([]int, 0) |
|||
max, _ := strconv.Atoi(os.Args[1]) |
|||
for i := 3; i < max; i += 2 { |
|||
isPrime := true |
|||
for j := 3; j <= int(math.Ceil(math.Sqrt(float64(i)))); j += 2 { |
|||
if i%j == 0 { |
|||
isPrime = false |
|||
break |
|||
} |
|||
} |
|||
if isPrime { |
|||
primes = append(primes, i) |
|||
} |
|||
} |
|||
fmt.Println(primes) |
|||
} |
@ -0,0 +1,28 @@ |
|||
use std::env; |
|||
|
|||
fn main() { |
|||
let args: Vec<String> = env::args().collect(); |
|||
if args.len() != 2 { |
|||
println!("Usage: ./primes $MAX"); |
|||
return; |
|||
} |
|||
let max: u64 = args[1].parse().expect("MAX must be an integer value"); |
|||
let mut i: u64 = 3; |
|||
|
|||
while i <= max {
|
|||
let loop_max: u64 = (i as f64).sqrt() as u64; |
|||
let mut x: u64 = 2; |
|||
let mut prime = true; |
|||
while x <= loop_max { |
|||
if i % x == 0 {
|
|||
prime = false; |
|||
break; |
|||
} |
|||
x += 1; |
|||
} |
|||
if prime { |
|||
println!("{}", i) |
|||
} |
|||
i += 2; |
|||
} |
|||
} |
Loading…
Reference in new issue