tcl - Print all prime numbers in range -


how print prime numbers in given range? here code tried, it's not giving correct output:

for {set x 2} {$x<100} {incr x} {      {set 2} {$i<$x} {incr i} {          set y [expr $x % $i]         set flag 0         if {$y == 0}  {             puts "$x:not prime no"             incr flag             break            }     }      if {$flag ==1} {         puts "$x: prime no"     } } 

finding prime numbers pretty explained out there[1][2], i'll explain bit more how should thinking in order work out solution. that, hope you'll better able answer such problems in future.

to start with, you've got 2 problems here. 1 problem how discover if particular number prime number, , problem how find prime numbers in given range. these 2 indeed linked: can use solution 1 solve other. let's start doing that. (this pseudocode, not tcl!)

# start @ 2; 1 defined non-prime every in 2 100     if (isprime i)         print i, " prime"     else         print i, " not prime"     end if end 

next, need mechanism isprime. it's that's best written named subprogram (a procedure in tcl). we'll use simplest technique here, primality test simple-minded trial division.

function isprime (integer x) : boolean     # note, when x 2, loop *zero* steps     every in 2 x-1         if (x mod = 0)             # exit function; know answer more work!             return false         end if     end     return true end function 

that's not efficient (you can stop earlier, can keep cache of smaller primes have been found , check against those, etc.) work. need convert above tcl. there's pretty straight-forward one-to-one conversion strategy.

but important part break overall challenge down simpler pieces can solve in way simple can't wrong.


side note: should brace expressions in tcl! not doing occasionally useful in advanced programming, it's bug waiting happen. has benefit of allowing built-in compiler turn expression fast code.


Comments