Module: Euler

Extended by:
Euler
Included in:
Euler
Defined in:
lib/euler.rb

Overview

The module that contains all the methods.

Defined Under Namespace

Modules: IntegerMethods

Constant Summary collapse

VERSION =
"1.0.3"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#fibonaccisObject (readonly)

Returns the value of attribute fibonaccis.



5
6
7
# File 'lib/euler.rb', line 5

def fibonaccis
  @fibonaccis
end

#primesObject (readonly)

Returns the value of attribute primes.



5
6
7
# File 'lib/euler.rb', line 5

def primes
  @primes
end

#sieveObject (readonly)

Returns the value of attribute sieve.



5
6
7
# File 'lib/euler.rb', line 5

def sieve
  @sieve
end

Instance Method Details

#find_missing_pyth_value(a, b, c) ⇒ Object

Given two values of a pythagorean triplet, and nil for the missing value, it returns the missing value.

Euler.find_missing_pyth_value(nil, 4, 5) # => 3


169
170
171
172
173
# File 'lib/euler.rb', line 169

def find_missing_pyth_value(a, b, c)
  return Math.sqrt(c**2 - b**2) if a.nil?
  return Math.sqrt(c**2 - a**2) if b.nil?
  return Math.sqrt(a**2 + b**2) if c.nil?
end

#generate_sieve(max) ⇒ Object

A basic prime sieve. Sets Euler.sieve to an array of boolean values that indicate if that index if prime or not.

Euler.generate_sieve(50)
Euler::sieve[2] # => true
Euler::sieve[4] # => false


120
121
122
123
124
125
126
127
128
129
# File 'lib/euler.rb', line 120

def generate_sieve(max)
  @sieve = Array.new(max, false)
  @sieve[2] = true
  3.step(max, 2) { |x| @sieve[x] = true}
  3.step(Math.sqrt(max).to_i, 2) { |i|
    if @sieve[i]
      (i**2).step(max, 2*i) { |x| @sieve[x] = false}
    end
  }
end

#get_fibonaccis(n) ⇒ Object

Sets Euler::fibonaccis to an array of integers which are the Fibonacci sequence of length n

Euler.get_fibonaccis(50)
Euler::fibonaccis[0] # => 1
Euler::fibonaccis[4] # => 5


151
152
153
154
155
156
157
# File 'lib/euler.rb', line 151

def get_fibonaccis(n)
  @fibonaccis, phi = [], (1+Math.sqrt(5))/2
  sqrt_5 = Math.sqrt(5)
  0.upto(n) do |x|
    @fibonaccis << (phi**(x+1)/sqrt_5).round
  end
end

#get_primes(n) ⇒ Object

A more advanced prime sieve. Generates an n amount of prime values.

Euler.get_primes(50)
Euler::primes[0] # => 2
Euler::primes[2] # => 5


135
136
137
138
139
140
141
142
143
144
# File 'lib/euler.rb', line 135

def get_primes(n)
  counter, current_value, @primes = 0, 2, []
  while counter < n
    if current_value.prime?
      @primes << current_value 
      counter += 1
    end
    current_value += 1
  end
end

#is_pythagorean_triplet?(a, b, c) ⇒ Boolean

Determines if the three values given are a pythagorean triplet

Euler.is_pythagorean_triplet?(3, 4, 5) # => true
Euler.is_pythagorean_triplet?(1, 2, 3) # => false

Returns:

  • (Boolean)


162
163
164
# File 'lib/euler.rb', line 162

def is_pythagorean_triplet?(a, b, c)
  a**2 + b**2 == c**2
end