ewall (owner)

Revisions

gist: 215600 Download_button fork
public
Description:
#merug Ruby Games 004 entry
Public Clone URL: git://gist.github.com/215600.git
Embed All Files: show embed
problem.rb #
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Problem < ActiveResource::Base
 
=begin
 
pseudocode:
prime = prime number generator (sadly, this is slow)
count = generate incremental odd numbers after 2 (2,3,5,7,9,11...)
 
loop while n>1
t = get next number to test
if n % t = 0:
answers << t
n = n / t
 
=end
 
  def self.root(n)
    Problem.root_with_generators(n)
  end
  
  def self.root_original_method(n)
    #require 'mathn'
    #prime = Prime.new
    answers=[]
    while n > 1 do
      t = Problem.count(p)
      #t = prime.next()
      while n % t == 0
        answers << t
        n = n / t
      end
    end
    answers
  end
 
  def self.count(i)
    i||=0 #if i was not given, start at 0
    #i==2 ? 3 : i+2 #return 3 if i==2, else return i+2
    i==2 ? i=3 : i+=2 #return 3 if i==2, else add 2 to i
    sum_of_digits = i.to_s.split("").inject(0) { |tot, d| tot + d.to_i }
    if sum_of_digits % 3 == 0
      return count(i)
    else
      return i
    end
  end
 
  ######################################################################
 
  def self.root_with_generators(n)
      answers=[]
      get_next_prime() do |t|
        puts t
        while n % t == 0 #we found a factor
          answers << t
          n = n / t #now reduce n
        end
        break if n == 1 #we've found all the factors
      end
      answers
  end
 
  def self.get_next_inc()
    #generator yields sequence (2,3,previous+2..)
    yield 2
    yield i = 3
    while true
      i += 2
      sum_of_digits = i.to_s.split("").inject(0) { |tot, d| tot + d.to_i }
      if sum_of_digits % 3 == 0 #skip this one if its divisible by 3
        i += 2
      end
      yield i
    end
  end
 
  def self.get_next_prime()
    #generator yields prime numbers one at a time
    require 'mathn'
    prime = Prime.new
    while true
      yield prime.next()
    end
  end
 
end