Wednesday, April 13, 2011

Project Euler - Problem 7 - Tcl

#By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#What is the 10001st prime number?
proc problem7-v2 {} {
 # Much faster.
 #REMARK: Based on problem-3
 set primes [list 2 3]
 set current_number 5
 set primes_found 2

 set finished FALSE
 while { !$finished } {

  set is_prime TRUE
  foreach prime $primes {
   if { ( $current_number % $prime ) == 0  } {
    set is_prime FALSE
    break
   }

   if { $prime >  ($current_number / 2) } {
    # Can't be bigger than factor 2!
    break
   }
  }

  if { $is_prime } {
   incr primes_found 1
   set last_prime $current_number
   lappend primes $last_prime
  }

  set finished [expr $primes_found == 10001]

  incr current_number 2
 }

 puts "solution-7: [lindex $primes end]"
}

# solution-7: solution-7: 104743

No comments:

Post a Comment