-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsieve.nim
More file actions
60 lines (49 loc) · 1.41 KB
/
sieve.nim
File metadata and controls
60 lines (49 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import math, sequtils, os, strutils
var limit: int
if paramCount() > 0:
try:
limit = parseInt(paramStr(1))
except ValueError:
echo "Error: Invalid number provided as command-line argument."
quit(1)
else:
while true:
stdout.write "Find prime numbers up to: "
try:
limit = parseInt(readLine(stdin))
break
except ValueError:
echo "Invalid input. Please enter an integer."
let limit_root = int(sqrt(float(limit)))
var isPrime = newSeqWith(limit + 1, true)
isPrime[0] = false
isPrime[1] = false
for p in 2..limit_root:
if isPrime[p]:
var i = p * p
while i <= limit:
isPrime[i] = false
i += p
let primes = toSeq(2..limit).filter(proc(i: int): bool = isPrime[i])
echo "Found ", primes.len, " prime numbers up to ", limit, ":"
#echo primes
while true:
stdout.write "Do you want to find the Nth prime? (y/n): "
let choice = readLine(stdin).strip().toLower()
if choice == "y":
while true:
stdout.write "Enter N: "
try:
let n_str = readLine(stdin)
let n = parseInt(n_str)
if n > 0 and n <= primes.len:
echo "The ", n, "th prime is: ", primes[n-1]
break
else:
echo "N must be between 1 and ", primes.len, "."
except ValueError:
echo "Invalid input. Please enter an integer for N."
elif choice == "n":
break
else:
echo "Invalid choice. Please enter 'y' or 'n'."