Advertisement
Guest User

Untitled

a guest
Apr 27th, 2014
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. [kilk@klkpc ruby_small]$ rb comp.rb
  2. Elapsed time for Brute Force : 5.804927 Primes = 78498
  3. Elapsed time for Sieve of Eratosthenes: 0.482605 Primes = 78498
  4. Elapsed time for Sieve of Sundaram : 0.650439 Primes = 78498
  5.  
  6. [kilk@klkpc crystal]$ bin/crystal test1.cr --run
  7. Elapsed time for Brute Force : 0.327009 Primes = 78498
  8. Elapsed time for Sieve of Eratosthenes: 0.0609334 Primes = 78498
  9. Elapsed time for Sieve of Sundaram : 0.0452578 Primes = 78498
  10.  
  11.  
  12.  
  13. def bruteForce(topCandidate)
  14. totalCount = 1
  15. isPrime = true
  16.  
  17. 3.step(topCandidate, 2) do |i|
  18. j=3
  19.  
  20. while j*j <= i && isPrime
  21. isPrime = false if i%j==0
  22. j += 2
  23. end
  24.  
  25. isPrime ? (totalCount += 1) : (isPrime = true)
  26. end
  27.  
  28. totalCount
  29. end
  30.  
  31. def sieveOfEratosthenes(topCandidate)
  32. myBA1 = Array.new(topCandidate + 1) {true}
  33. myBA1[0] = myBA1[1] = false
  34. thisFactor = 2
  35.  
  36. while thisFactor * thisFactor <= topCandidate
  37. mark = thisFactor + thisFactor
  38. mark.step(topCandidate, thisFactor) {|n| myBA1[n] = false}
  39.  
  40. thisFactor += 1
  41.  
  42. while (!myBA1[thisFactor])
  43. thisFactor += 1
  44. end
  45.  
  46. end
  47.  
  48. myBA1.count(true)
  49. end
  50.  
  51. def sieveOfSundaram(topCandidate)
  52. k = topCandidate / 2
  53. myBA1 = Array.new(k + 1) {true}
  54. myBA1[0] = myBA1[k] = false
  55.  
  56. (1..k).each do |i|
  57. denominator = (i << 1) + 1
  58. maxVal = (k - i) / denominator
  59. i.step(maxVal, 1) {|n| myBA1[i + n * denominator] = false}
  60.  
  61. # this version takes .20 seconds longer to run 1M iterations!
  62. # for n in i..maxVal+1 do
  63. # myBA1[i + n * denominator] = false
  64. # end
  65. end
  66.  
  67. myBA1.count(true) + 1
  68. end
  69.  
  70. def main
  71. max = 1000000
  72. startTime = Time.now()
  73. primes = bruteForce(max)
  74. elapsed = Time.now() - startTime
  75. puts("Elapsed time for Brute Force : #{elapsed} Primes = #{primes}")
  76.  
  77. startTime = Time.now()
  78. primes = sieveOfEratosthenes(max)
  79. endTime = Time.now()
  80. elapsed = endTime - startTime
  81. puts("Elapsed time for Sieve of Eratosthenes: #{elapsed} Primes = #{primes}")
  82.  
  83. startTime = Time.now()
  84. primes = sieveOfSundaram(max)
  85. endTime = Time.now()
  86. elapsed = endTime - startTime
  87. puts("Elapsed time for Sieve of Sundaram : #{elapsed} Primes = #{primes}")
  88. end
  89.  
  90. main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement