Skip to content

Commit b8dc474

Browse files
authored
Add Prime Number in Tcl (#5074)
1 parent 23505e8 commit b8dc474

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

archive/t/tcl/prime-number.tcl

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package require Tcl 8.6
2+
package require math::numtheory
3+
4+
proc usage {} {
5+
puts stderr {Usage: please input a non-negative integer}
6+
exit 1
7+
}
8+
9+
proc isNonNegativeInteger {s} {
10+
if {[catch {expr {int($s)}} n]} {
11+
return 0
12+
}
13+
if {$s eq ""} { return 0 }
14+
if {![string is integer -strict $s]} {
15+
return 0
16+
}
17+
return [expr {$n >= 0}]
18+
}
19+
20+
if {$argc != 1} { usage }
21+
22+
set input [string trim [lindex $argv 0]]
23+
if {![isNonNegativeInteger $input]} { usage }
24+
25+
set n $input
26+
if {$n < 2} {
27+
puts "composite"
28+
} elseif {[math::numtheory::isprime $n]} {
29+
puts "prime"
30+
} else {
31+
puts "composite"
32+
}
33+

0 commit comments

Comments
 (0)