Class: Integer

Inherits:
Object
  • Object
show all
Defined in:
lib/numb.rb,
lib/numb/q.rb,
lib/numb/lah.rb,
lib/numb/nsw.rb,
lib/numb/aban.rb,
lib/numb/base.rb,
lib/numb/bell.rb,
lib/numb/blum.rb,
lib/numb/core.rb,
lib/numb/eban.rb,
lib/numb/evil.rb,
lib/numb/iban.rb,
lib/numb/oban.rb,
lib/numb/self.rb,
lib/numb/uban.rb,
lib/numb/brown.rb,
lib/numb/carol.rb,
lib/numb/demlo.rb,
lib/numb/happy.rb,
lib/numb/keith.rb,
lib/numb/knuth.rb,
lib/numb/kynea.rb,
lib/numb/lucas.rb,
lib/numb/nexus.rb,
lib/numb/proth.rb,
lib/numb/words.rb,
lib/numb/achain.rb,
lib/numb/choose.rb,
lib/numb/cullen.rb,
lib/numb/cyclic.rb,
lib/numb/euclid.rb,
lib/numb/fermat.rb,
lib/numb/franel.rb,
lib/numb/frugal.rb,
lib/numb/knodel.rb,
lib/numb/lucas2.rb,
lib/numb/mobius.rb,
lib/numb/ménage.rb,
lib/numb/odious.rb,
lib/numb/perrin.rb,
lib/numb/poulet.rb,
lib/numb/primes.rb,
lib/numb/pronic.rb,
lib/numb/zeisel.rb,
lib/numb/beastly.rb,
lib/numb/catalan.rb,
lib/numb/dudeney.rb,
lib/numb/hamming.rb,
lib/numb/hilbert.rb,
lib/numb/idoneal.rb,
lib/numb/leyland.rb,
lib/numb/lychrel.rb,
lib/numb/motzkin.rb,
lib/numb/ordinal.rb,
lib/numb/repunit.rb,
lib/numb/reverse.rb,
lib/numb/sphenic.rb,
lib/numb/størmer.rb,
lib/numb/super_d.rb,
lib/numb/totient.rb,
lib/numb/unhappy.rb,
lib/numb/vampire.rb,
lib/numb/woodall.rb,
lib/numb/amenable.rb,
lib/numb/binomial.rb,
lib/numb/congruum.rb,
lib/numb/delannoy.rb,
lib/numb/divisors.rb,
lib/numb/figurate.rb,
lib/numb/genocchi.rb,
lib/numb/gnomonic.rb,
lib/numb/goldbach.rb,
lib/numb/kaprekar.rb,
lib/numb/leonardo.rb,
lib/numb/mersenne.rb,
lib/numb/mms_pair.rb,
lib/numb/positive.rb,
lib/numb/schröder.rb,
lib/numb/stirling.rb,
lib/numb/takeuchi.rb,
lib/numb/zerofree.rb,
lib/numb/bernoulli.rb,
lib/numb/cototient.rb,
lib/numb/entringer.rb,
lib/numb/factorial.rb,
lib/numb/factorion.rb,
lib/numb/fibonacci.rb,
lib/numb/integer_p.rb,
lib/numb/parasitic.rb,
lib/numb/primorial.rb,
lib/numb/segmented.rb,
lib/numb/stirling2.rb,
lib/numb/carmichael.rb,
lib/numb/idempotent.rb,
lib/numb/palindrome.rb,
lib/numb/pandigital.rb,
lib/numb/pell_lucas.rb,
lib/numb/persistent.rb,
lib/numb/properties.rb,
lib/numb/trimorphic.rb,
lib/numb/undulating.rb,
lib/numb/apocalyptic.rb,
lib/numb/automorphic.rb,
lib/numb/biquadratic.rb,
lib/numb/consecutive.rb,
lib/numb/doubly_even.rb,
lib/numb/in_sequence.rb,
lib/numb/prime_power.rb,
lib/numb/quarticfree.rb,
lib/numb/reciprocity.rb,
lib/numb/singly_even.rb,
lib/numb/modulo_order.rb,
lib/numb/narcissistic.rb,
lib/numb/nivenmorphic.rb,
lib/numb/noncototient.rb,
lib/numb/refactorable.rb,
lib/numb/subfactorial.rb,
lib/numb/nonhypotenuse.rb,
lib/numb/polydivisible.rb,
lib/numb/super_catalan.rb,
lib/numb/primitive_root.rb,
lib/numb/sum_of_squares.rb,
lib/numb/primitive_roots.rb,
lib/numb/divisors/aliquot.rb,
lib/numb/divisors/perfect.rb,
lib/numb/jacobsthal_lucas.rb,
lib/numb/lucas_carmichael.rb,
lib/numb/n_step_fibonacci.rb,
lib/numb/self_descriptive.rb,
lib/numb/divisors/abundant.rb,
lib/numb/divisors/amicable.rb,
lib/numb/smarandache_wellin.rb,
lib/numb/strictly_non_palindromic.rb

Constant Summary collapse

BASE =
{
        binary:          2, ternary:       3, quaternary:     4,
        quinary:         5, senary:        6, septenary:      7, 
        octal:           8, nonary:        9, decimal:       10, 
        undecimal:      11, duodecimal:   12, tridecimal:    13,
        tetradecimal:   14, pentadecimal: 15, hexadecimal:   16,
        septendecimal:  17, decennoctal:  18, decennoval:    19,
        vigesimal:      20, trigesimal:   30, quadragesimal: 40,
        quinquagesimal: 50, sexagesimal:  60, septuagesimal: 70,
        octagesimal:    80, nonagesimal:  90, centesimal:   100,
        millesimal:  1_000
}
WORDS =
{
  0 => 'zero', 1 => 'one', 2 => 'two', 3 => 'three',   4 => 'four',
  5 => 'five', 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine',
  10 => 'ten', 11 => 'eleven', 12 => 'twelve', 13 => 'thirteen', 
  14 => 'fourteen', 15 => 'fifteen', 16 => 'sixteen', 17 => 'seventeen', 
  18 => 'eighteen', 19 => 'nineteen', 20 => 'twenty', 30 => 'thirty', 
  40 => 'forty', 50 => 'fifty', 60 => 'sixty', 70 => 'seventy', 
  80 => 'eighty', 90 => 'ninety'
}
SPECIAL_DECOMP =

Special cases not handled by the following algorithm

{
  2 => [1, 1], 3 => [1, 1, 1], 10 => [1, 3], 34 => [3, 3, 4], 
  58 => [3, 7], 85 => [6, 7], 130 => [3, 11], 214 => [3, 6, 13],
  226 => [8, 9, 9], 370 => [8, 9, 15], 526 => [6, 7, 21], 
  706 => [15, 15, 16], 730 => [1, 27], 1414 => [6, 17, 33],
  1906 => [13, 21, 36], 2986 => [21, 32, 39], 9634 => [56, 57, 57],
}

Instance Method Summary collapse

Instance Method Details

#aban?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/aban.rb', line 2

def aban?
  not words.sub(/and/,'').include?('a')
end

#abundancyObject



21
22
23
# File 'lib/numb/divisors/abundant.rb', line 21

def abundancy
  Rational(σ, self)
end

#abundant?Boolean Also known as: excessive?

An abundant number is a number n for which σ(n) > 2n. That is, the sum of its divisors exceeds 2n. (See Integer#σ to compute the sum of the divisors of an arbitrary integer).

Returns true if the number is abundant; false otherwise. Aliased to Integer#excessive?.

96.abundant?   #=> true
100.abundant?  #=> true
345.abundant?  #=> false

Returns:

  • (Boolean)


14
15
16
17
# File 'lib/numb/divisors/abundant.rb', line 14

def abundant?
  return false unless positive?
  σ > (2 * self)
end

#achainObject



95
96
97
98
# File 'lib/numb/achain.rb', line 95

def achain
  self == 1 ? [1] 
            : [AChain.factor(self), AChain.window_brute(self)].min_by(&:size)
end

#achilles?Boolean

An Achilles number is powerful but not a perfect power.

Returns true if self is an Achilles number; false otherwise.

1152.achilles?  #=> true
4563.achilles?  #=> true
100.achilles?   #=> false

Returns:

  • (Boolean)


45
46
47
# File 'lib/numb/divisors.rb', line 45

def achilles?
  powerful? and not perfect_power?
end

#aliquot_sequence(max_iterations = (self > 100 ? 10 : sqrt), summatory_function = ->(n){ n.aliquot_sum }) ⇒ Object



3
4
5
6
7
8
9
10
11
12
# File 'lib/numb/divisors/aliquot.rb', line 3

def aliquot_sequence(max_iterations=(self > 100 ? 10 : sqrt),
                     summatory_function=->(n){ n.aliquot_sum })
  sequence = [self]
  max_iterations.floor.times do |limit|
    sequence << summatory_function[sequence.last]
    break if sequence[0..-2].include?(sequence.last)
    return sequence << (1/0.0) if limit.consecutive?(max_iterations)
  end
  sequence
end

#aliquot_sumObject



143
144
145
146
# File 'lib/numb/divisors.rb', line 143

def aliquot_sum
  return 0 if zero?
  σ - self
end

#almost_perfect?Boolean Also known as: least_deficient?, slightly_defective?

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/numb/divisors/perfect.rb', line 34

def almost_perfect?
  return true if self == 1
  proper_divisors.reduce(:+) == self - 1
end

#almost_prime?(k) ⇒ Boolean

Returns:

  • (Boolean)


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

def almost_prime?(k)
  Ω == k
end

#amenable?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/amenable.rb', line 2

def amenable?
  self != 4 and modulo(4) < 2
end

#amicable?(other) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
# File 'lib/numb/divisors/amicable.rb', line 8

def amicable?(other)
  n, m = [self, other].minmax
  m.multiamicable?(n, 1, 1)
end

#apocalyptic?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/apocalyptic.rb', line 2

def apocalyptic?
  (2**self).to_s.include?('666')
end

#aspiring?(max_iterations = 10) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
# File 'lib/numb/divisors/aliquot.rb', line 25

def aspiring?(max_iterations=10)
  return false if perfect? 
  (last = aliquot_sequence(max_iterations).last).to_f.finite? ? 
    last.perfect? : 
    false
end

#augmented_amicable?(n) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
# File 'lib/numb/divisors/amicable.rb', line 13

def augmented_amicable?(n)
  m = self
  [m.σ, n.σ].all?{|sigma| sigma == m + n - 1}
end

#automorphic?(n = 1) ⇒ Boolean Also known as: curious?

An automorphic number is a number whose square terminates in the number itself. That is, k is automorphic if the final digits of k<sup>2</sup> are the digits of k.

More generally, an n-automorphic number is one of the form nk<sup>2</sup> which has its last digits equal to k. n may be supplied as an argument to this method; otherwise it defaults to 1.

Returns true if the number is automorphic; false otherwise. Aliased to Integer#curious?.

25.automorphic?    #=> true
9376.automorphic?  #=> true
600.automorphic?   #=> true

Returns:

  • (Boolean)


20
21
22
# File 'lib/numb/automorphic.rb', line 20

def automorphic?(n=1)
  (n * self ** 2).to_s.end_with? self.to_s
end

#balanced_prime?Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
16
# File 'lib/numb/primes.rb', line 9

def balanced_prime?
  return false unless prime? and self >= 5
  primes, before = Prime.each, 2
  primes.each do |prime|
    return ((before + primes.next) / 2) == self if prime == self
    before = prime
  end
end

#base(base = nil) ⇒ Object

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/numb/base.rb', line 15

def base(base=nil)
  return Hash[BASE.values.map{|b| [b, base(b)]}] unless base
  return '0' if zero?
  base = case base
           when Numeric        then base.to_int
           when String, Symbol then BASE[base.downcase.to_sym]
           else                     nil
         end
  raise ArgumentError unless base and base > 1
  begin
    to_s(base)
  rescue ArgumentError
    chars = [*(0..9)] + [*('a'..'z')]
    (base - chars.size).times { chars.push(chars.last.succ) }
    n, digits = self, []
    until n.zero?
      n, remainder = n.divmod(base)
      digits << chars[remainder]
    end
    digits.reverse.join
  end
end

#beastly?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/beastly.rb', line 2

def beastly?
  to_s.include?('666')
end

#bellObject



6
7
8
9
10
# File 'lib/numb/bell.rb', line 6

def bell
  n = self
  return 1 if zero?
  (0..(n-1)).map{|k| k.bell * (n-1).choose(k)}.reduce(:+)
end

#bell?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/bell.rb', line 2

def bell?
  in_sequence?(seq: :bell)
end

#bernoulliObject

TODO: Consider cims.nyu.edu/~harvey/bernmm/



4
5
6
7
8
9
10
# File 'lib/numb/bernoulli.rb', line 4

def bernoulli
  return 1 if zero?
  m = self
  (m.zero? ? 1 : 0) - (0...m).map do |k| 
    m.choose(k) * Rational(k.bernoulli, m - k + 1)
  end.reduce(:+)
end

#betrothed?(m) ⇒ Boolean Also known as: quasi_amicable?, reduced_amicable?

Returns:

  • (Boolean)


18
19
20
# File 'lib/numb/divisors/amicable.rb', line 18

def betrothed?(m)
  σ == m.σ and consecutive?(σ - m)
end

#binomial?(exp = 4) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/numb/binomial.rb', line 2

def binomial?(exp=4)
  x = self
  return true if (0..2).include? x
  (2..exp).each do |n|
    (1...x).each do |a|
      an = a**n
      sign, *terms = an > x ? [:-, an, x] : [:+, x, an]
      b = (terms.reduce(:-))**(1.0/n.to_f)
      return true if b.integer? and x == an.send(sign, b**n)
    end
  end
  false
end

#biquadratic?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/biquadratic.rb', line 2

def biquadratic?
  (self ** (1.0/4.0)).integer?
end

#blum?Boolean

Returns:

  • (Boolean)


2
3
4
5
# File 'lib/numb/blum.rb', line 2

def blum?
  return false unless prime_factors.size == 2
  prime_factors.uniq.size == 2 and prime_factors.all?{|p| p.modulo(4) == 3}
end

#breeder?(b) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
# File 'lib/numb/divisors/amicable.rb', line 25

def breeder?(b)
  a = self
  x = (a.σ - a).fdiv(b)
  abx = a + (b*x)
  (abx == a.σ) and (abx == b.σ * (x + 1))
end

#brilliant?Boolean

Returns:

  • (Boolean)


56
57
58
59
# File 'lib/numb/divisors.rb', line 56

def brilliant?
  pfacts = prime_factors
  pfacts.size == 2 and pfacts.map{|f| f.to_s.size}.uniq.size == 1
end

#brown?(n) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/brown.rb', line 2

def brown?(n)
  n.factorial.consecutive?(self ** 2)
end

#carmichaelObject



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/numb/carmichael.rb', line 9

def carmichael
  case self
    when 1, 2 then 1
    when 4 then 2
    else
      if primaries.size == 1
        p, a = primaries.first
        return totient if p.odd?
        return totient/2 if p == 2 and a >= 3
      end
      primaries.map{|p| p.reduce(:**)}.map(&:carmichael).reduce(&:lcm)
  end
end

#carmichael?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
# File 'lib/numb/carmichael.rb', line 2

def carmichael?
  return false unless odd? and composite? and square_free?
  prime_factors.all? do |p|
    (self - 1).remainder(p - 1) == 0
  end
end

#carol?Boolean

A Carol number is an integer of the form 4<sup>n</sup> − 2<sup>n + 1</sup> − 1.

This method returns true if self is a Carol number; false otherwise.

−1.carol?  #=> true 
959.carol? #=> true 
32.carol?  #=> false

Returns:

  • (Boolean)


14
15
16
17
18
19
20
# File 'lib/numb/carol.rb', line 14

def carol?
  return true if self == 7
  return true if self == -1
  a, b = to_s(2).match(/^(1+)0(1+)$/).to_a[1..-1]
  return false if (a.nil? or b.nil?)
  b.length == (a.length + 3)
end

#catalanObject



2
3
4
# File 'lib/numb/catalan.rb', line 2

def catalan
  (2*self).factorial / (succ.factorial * factorial)
end

#catalan?Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/numb/catalan.rb', line 6

def catalan?
  in_sequence?(seq: :catalan)
end

#centered_cube?Boolean

Returns:

  • (Boolean)


28
29
30
31
32
# File 'lib/numb/figurate.rb', line 28

def centered_cube?
  1.upto(Math.cbrt(self)).any? do |n|
    self == n**3 + (n - 1) ** 3
  end
end

#centered_hexagonal?Boolean

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/numb/figurate.rb', line 34

def centered_hexagonal?
  n = self - 1
  n.divides?(6) and (n/6).triangular?
end

#centered_n_gonal?(n) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


20
21
22
23
24
25
26
# File 'lib/numb/figurate.rb', line 20

def centered_n_gonal?(n)
  raise ArgumentError unless n > 2
  Rational(
    -n + Math.sqrt( n**2 - 8 * (n - n * self) ), 
                2 * n
  ).denominator == 1
end

#centered_pentagonal?Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/numb/figurate.rb', line 39

def centered_pentagonal?
  n = self - 1
  n.divides?(5) and (n/5).triangular?
end

#centered_square?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/numb/figurate.rb', line 44

def centered_square?
  centered_n_gonal? 4
end

#centered_triangular?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/numb/figurate.rb', line 48

def centered_triangular?
  centered_n_gonal?(3)
end

#chen_prime?Boolean

Returns:

  • (Boolean)


170
171
172
# File 'lib/numb/primes.rb', line 170

def chen_prime?
  prime? and (succ.succ.prime? or succ.succ.semiprime?)
end

#choose(k) ⇒ Object Also known as: binomial_coefficient



3
4
5
# File 'lib/numb/choose.rb', line 3

def choose(k)
  k > self ? 0 : factorial / (k.factorial * (self - k).factorial)
end

#composite?Boolean

Returns:

  • (Boolean)


132
133
134
# File 'lib/numb/primes.rb', line 132

def composite?
  self > 1 and not prime?
end

#congruum?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
# File 'lib/numb/congruum.rb', line 2

def congruum?
  # Fibonacci proved that h|24
  # Fermat’s right triangle theorem shows h is not square
  return false unless divides?(24) and not square?
  h = self
  (1..Math.sqrt(h)).any? do |n|
    (n.succ..Math.sqrt(h)).any? do |m|
      h == (4 * m * n) * (m**2 - n**2)
    end
  end
end

#consecutive?(m) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/consecutive.rb', line 2

def consecutive?(m)
  self == m.succ or succ == m
end

#coprime?(x) ⇒ Boolean Also known as: , stranger?

Returns:

  • (Boolean)


61
62
63
# File 'lib/numb/divisors.rb', line 61

def coprime?(x)
  gcd(x) == 1
end

#coreObject

Raises:

  • (ArgumentError)


3
4
5
6
# File 'lib/numb/core.rb', line 3

def core
  raise ArgumentError if self <= 0
  divisors.sort.select{|m| (self/m).square?}.first
end

#cototientObject



3
4
5
# File 'lib/numb/cototient.rb', line 3

def cototient
  self - φ
end

#cube?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/numb/figurate.rb', line 52

def cube?
  Math.cbrt(self).integer?
end

#cubic_residue?(p) ⇒ Boolean

Returns:

  • (Boolean)


7
8
9
# File 'lib/numb/reciprocity.rb', line 7

def cubic_residue?(p)
  coprime?(p) and residue? p, 3
end

#cullen?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
# File 'lib/numb/cullen.rb', line 2

def cullen?
  return true if self == 1
  factors = (self - 1).divisors.sort
  factors.first(factors.size/2).any?{|n| n * 2**n + 1 == self}
end

#cyclic?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
# File 'lib/numb/cyclic.rb', line 2

def cyclic?
  return true if zero?
  return false unless digits.size >= 6
  nzd = nonzero_digits.sort
  (1...digits.size).all?{|n| (self * n).nonzero_digits.sort == nzd}
end

#d?Boolean

Returns:

  • (Boolean)


179
180
181
# File 'lib/numb/divisors.rb', line 179

def d?
  knödel?(3)
end

#decagonal?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/numb/figurate.rb', line 56

def decagonal?
  n_gonal?(10)
end

#deficient?Boolean Also known as: defective?

A deficient number is a number n for which σ(n) < 2n. That is, the sum of its divisors are less than the number. (To calculate the sum of divisors for an arbitrary integer see Integer#σ).

Returns true if the number is deficient; false otherwise.

8.deficient?  #=> true
27.deficient? #=> true
6.deficient?  #=> false

Returns:

  • (Boolean)


78
79
80
81
# File 'lib/numb/divisors.rb', line 78

def deficient?
  return false unless positive?
  σ < (2 * self)
end

#delannoy(b) ⇒ Object



20
21
22
23
24
# File 'lib/numb/delannoy.rb', line 20

def delannoy(b)
  a = self
  return 1 if b.zero? or a.zero?
  [(a - 1).delannoy(b), a.delannoy(b - 1), (a - 1).delannoy(b - 1)].reduce(:+)
end

#delannoy?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/numb/delannoy.rb', line 2

def delannoy?
  return true if self == 1
  max_a, max_b = self/2, self/2
  (1..max_a).each do |a|
    (1..max_b).each do |b|
      d = a.delannoy(b)
      return true if d == self
      if d > self
        max_b = b 
        max_a = a
        break
      end
    end
    break if a > max_a
  end
  false
end

#demloObject



2
3
4
# File 'lib/numb/demlo.rb', line 2

def demlo
  repunit ** 2
end

#demlo?Boolean

Returns:

  • (Boolean)


6
7
8
# File 'lib/numb/demlo.rb', line 6

def demlo?
  square? and isqrt.repunit?(10)
end

#digital_rootObject



28
29
30
# File 'lib/numb.rb', line 28

def digital_root
  self == 0 ? 0 : 1 + ((self - 1) % 9)
end

#digital_sumObject Also known as: sum_of_digits, sod



32
33
34
# File 'lib/numb.rb', line 32

def digital_sum
  digits.reduce(:+)
end

#digitsObject



38
39
40
# File 'lib/numb.rb', line 38

def digits
  self.to_s.split(//).map{|d| d.to_i}
end

#dihedral_prime?Boolean

A dihedral prime is a prime number that appears as itself or another prime when rendered on a seven-segment display of a calculator and…

  • Rotated 180°.

  • Mirrored.

  • Rotated 180° and mirrored.

For example, 120121 is a dihedral prime. It is 121021 when rotated, 151051 (another prime) when mirrored, and 150151 when rotated and mirrored.

Returns true if self is a dihedral prime; false otherwise.

101.dihedral_prime?  #=> true
181.dihedral_prime?  #=> true
7.dihedral_prime?    #=> false

Returns:

  • (Boolean)


35
36
37
38
39
# File 'lib/numb/primes.rb', line 35

def dihedral_prime?
  return false unless prime? and to_s.match(/^[01825]+$/)
  mirror = ->(n){ n.to_s.gsub(/([25])/){|orig| orig == '2' ? '5' : '2'}.to_i }
  [reverse, mirror[self], mirror[reverse]].all?(&:prime?)
end

#divides?(n) ⇒ Boolean

Returns:

  • (Boolean)


148
149
150
# File 'lib/numb/divisors.rb', line 148

def divides?(n)
  not n.zero? and (self % n).zero?
end

#divisorsObject



127
128
129
130
131
132
# File 'lib/numb/divisors.rb', line 127

def divisors
  return [] unless positive?
  return [1, self] if prime?
  (1..isqrt).select { |n| (self % n).zero? }.
             map {|n| [n, self/n]}.flatten.uniq
end

#dodecagonal?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/numb/figurate.rb', line 66

def dodecagonal?
  n_gonal?(12)
end

#doubly_even?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/doubly_even.rb', line 2

def doubly_even?
  modulo(4).zero?
end

#dudeney?Boolean

A Dudeney number is a positive integer that is a perfect cube such that the sum of its decimal digits is the cube root of the number.

Returns true if self is a Dudeney number; false otherwise.

4913.dudeney?  #=> true
5832.dudeney?  #=> true
98.dudeney?    #=> false

Returns:

  • (Boolean)


12
13
14
15
16
# File 'lib/numb/dudeney.rb', line 12

def dudeney?
  # The ugly hack below is seemingly needed for 1.8 compatibility. I ave
  # yet to understand why.
  Math.cbrt(self).to_s.sub(/\.0$/,'') == self.digits.reduce(:+).to_s
end

#e_divisorsObject



85
86
87
88
89
90
91
92
# File 'lib/numb/divisors.rb', line 85

def e_divisors
  return [1] if self == 1
  pfacts = primaries
  comb = pfacts.map{|p,a| (1..a).select{|b| a.divides?(b)}.map{|b| p**b}}
  comb.flatten.permutation(pfacts.size).select do |perm|
    perm.each_with_index.all?{|x,i| comb[i].include? x}
  end.map{|perm| perm.reduce(:*)}
end

#e_perfect?Boolean

Returns:

  • (Boolean)


42
43
44
45
# File 'lib/numb/divisors/perfect.rb', line 42

def e_perfect?
  return false if odd?
  σe == 2 * self
end

#eban?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/eban.rb', line 2

def eban?
  not words.include?('e')
end

#economical?Boolean

A number which is either frugal or equidigital.

Returns true if self is economical; false otherwise.

See also Integer#equidigital? and Integer#frugal?.

243.economical?  #=> true
7.economical?    #=> true
989.economical?  #=> false

Returns:

  • (Boolean)


193
194
195
# File 'lib/numb/divisors.rb', line 193

def economical?
  equidigital? or frugal?
end

#emrip?Boolean

An emrip is a prime whose reversed digits give a different prime. For example, 17 is an emrip because 71 is also prime.

Returns true if self is an emrip; false otherwise.

1009.emrip?  #=> true
1193.emrip?  #=> true
7.emrip?     #=> false

Returns:

  • (Boolean)


50
51
52
# File 'lib/numb/primes.rb', line 50

def emrip?
  prime? and reverse != self and reverse.prime?
end

#entringer(k) ⇒ Object



3
4
5
6
7
# File 'lib/numb/entringer.rb', line 3

def entringer(k)
  return 1 if zero? and k.zero?
  return 0 if (self < k or k < 0)
  entringer(k - 1) + (self - 1).entringer(self - k)
end

#equidigital?Boolean

An equidigital number has the same number of digits as the number of digits in its prime factorization (including exponents).

For example, 35 is equidigital because it has two digits and two 1-digit prime factors (5 and 7).

Returns true if self is equidigital; false otherwise.

81.equidigital?    #=> true
49.equidigital?    #=> true
1287.equidigital?  #=> false

Returns:

  • (Boolean)


209
210
211
# File 'lib/numb/divisors.rb', line 209

def equidigital?
  digits.size == primaries.flatten.reject{|d|d==1}.join.to_i.digits.size
end

#euclid?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/euclid.rb', line 2

def euclid?
  (self - 1).primorial?
end

#evil?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/evil.rb', line 2

def evil?
  not odious?
end

#extravagant?Boolean Also known as: wasteful?

An extravagant number has fewer digits than the number of digits in its prime factorization (including exponents).

Returns true if self is extravagant; false otherwise. Aliased to Integer#wasteful?.

234.extravagant?  #=> true
87.extravagant?   #=> true
81.extravagant?   #=> false

Returns:

  • (Boolean)


104
105
106
# File 'lib/numb/divisors.rb', line 104

def extravagant?
  digits.size < primaries.flatten.reject{|d|d==1}.join.to_i.digits.size
end

#factorialObject



2
3
4
5
# File 'lib/numb/factorial.rb', line 2

def factorial
  return 1 if zero?
  (1..self).reduce(:*)
end

#factorial?Boolean

Returns:

  • (Boolean)


7
8
9
10
11
12
13
14
15
16
# File 'lib/numb/factorial.rb', line 7

def factorial?
  divisors = self.divisors.sort
  divisors.each_with_index do |d, i|
    if divisors[i.succ] == d.succ
      return true if d.factorial == self
    else
      return d.factorial == self
    end
  end
end

#factorial_of?Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
27
28
# File 'lib/numb/factorial.rb', line 18

def factorial_of?
  return false unless factorial?
  return 1 if self == 1
  pfacts = primaries
  divisors.sort.take_while.with_index{|d,i| d == i.succ}.reverse_each do |d|
    pfacts.all? do |b, e|
      (1..Math.log(d,b)).map{|k| Rational(d, b**k).floor}.reduce(:+) == e
    end and return d
  end
  nil
end

#factorion?Boolean

A factorion is a number equal to the sum of the factorials of its decimal digits.

Returns true if self is a factorion; false otherwise.

145.factorion?    #=> true
40585.factorion?  #=> true
200.factorion?    #=> false

Returns:

  • (Boolean)


12
13
14
# File 'lib/numb/factorion.rb', line 12

def factorion?
  [1, 2, 145, 40585].include? self
end

#fermat?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/fermat.rb', line 3

def fermat?
  self > 2 and Math.log2(Math.log2(self - 1)).integer?
end

#fermat_pseudoprime?(a = 10) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


79
80
81
82
83
84
85
# File 'lib/numb/primes.rb', line 79

def fermat_pseudoprime?(a=10)
  return false unless composite?
  q = self
  raise ArgumentError unless a >= 2
  raise ArgumentError unless (q - 2) >= a
  (a**(q-1)).modulo(q) == 1
end

#fibonacci?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
# File 'lib/numb/fibonacci.rb', line 2

def fibonacci?
  return true if self == 1
  # Posamentier, Alfred; Lehmann, Ingmar (2007). The (Fabulous) FIBONACCI
  # Numbers. Prometheus Books. pp. 305
  [4, -4].map{|x| (5 * (self**2)) + x}.any? &:square?
end

#first_with_n_divisorsObject



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'lib/numb/divisors.rb', line 325

def first_with_n_divisors
  if zero? then 0
  elsif self == 1 then 1
  elsif not positive? then nil
  else
    pf = prime_factors
    if pf.uniq == [2]
      list = []
      Prime.each do |prime|
        break if prime > self
        list << prime
        exp = 1
        loop do
          pow2 = 2 ** exp
          break if pow2 > self
          prime **= pow2
          break if prime > self
          list << prime
        end
      end
      list.sort.uniq.first(pf.size).reduce(:*)
    else
      limit = Prime.first(pf.size).zip(pf.reverse).map{|b,e| b**(e-1)}.reduce(:*)
      neighbour = ->(e) { (self/e).divisors.reject{|d| d > e} }
      x, div, exponents = self, divisors, {}

      Prime.each do |b| 
        max_exponent = Math.log(limit, b).floor
        d = div.reject{|d| d > max_exponent}.sort.reverse - [1]
        unless b == 2
          prev_neighbours = exponents[exponents.keys.last].values.flatten
          d.reject!{|e, n| not prev_neighbours.include?(e)}
        end
        exponents[b] = Hash[d.map{|e| [e, neighbour.(e)]}]
        break if (x /= b) < 1
      end

      complete_chain = ->(b, e, goal=self, chain=nil) do
        chain ||= {chain: [[b, e]]}
        return chain unless exponents.key?(b) and exponents[b].key?(e)
        exponents[b][e].map do |n|
          this = {chain: chain[:chain].dup}
          this[:chain].pop if this[:chain].last.first == b.next_prime
          this[:chain] << [b.next_prime, n]
          e * n < goal ? complete_chain[b.next_prime, n, goal/e, this] : this
        end
      end

      exponents[2].keys.map do |e,|
        complete_chain[2, e].flatten.map{|c| Hash[c[:chain]]}.
          select{|c| c.values.reduce(:*) == self}.
          map{|c| c.map{|b,e| b**(e-1)}.reduce(:*)}.
          reject{|prod| prod > limit}
      end.flatten.min or limit
    end
  end
end

#franelObject



3
4
5
# File 'lib/numb/franel.rb', line 3

def franel
  (0..self).map{|k| choose(k) ** 3 }.reduce(:+)
end

#friendly?(*others) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


27
28
29
30
31
# File 'lib/numb/divisors/abundant.rb', line 27

def friendly?(*others)
  raise ArgumentError unless others.size >= 1 && others.uniq.size == others.size
  abundancy = self.abundancy
  others.all? {|o| o.abundancy == abundancy}
end

#frugal?Boolean

A frugal number has more digits than the number of digits in its prime factorization (including exponents).

Returns true if self is frugal; false otherwise.

128.frugal?  #=> true
256.frugal?  #=> true
300.frugal?  #=> false

Returns:

  • (Boolean)


13
14
15
# File 'lib/numb/frugal.rb', line 13

def frugal?
  digits.size > prime_division.flatten.reject{|d|d==1}.join.to_i.digits.size
end

#full_reptend_prime?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/numb/primes.rb', line 54

def full_reptend_prime?
  prime? and primitive_root?(10)
end

#genocchiObject



3
4
5
6
7
# File 'lib/numb/genocchi.rb', line 3

def genocchi
  return 1 if self == 1
  return 0 if odd?
  (2 * (1 - 2**self) * bernoulli).to_i
end

#giuga?Boolean

Returns:

  • (Boolean)


213
214
215
216
217
# File 'lib/numb/divisors.rb', line 213

def giuga?
  composite? and prime_factors.uniq.all? do |p|
    ((self / p) - 1).divides?(p)
  end
end

#goldbach?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
# File 'lib/numb/goldbach.rb', line 2

def goldbach?
  return false unless even? and self > 2
  #downto(2).any?{|n| n.prime? and (self - n).prime?}
  Prime.each do |prime|
    next if prime == 2
    return true if (self - prime).prime?
    return false if prime >= self
  end
end

#hamming?Boolean Also known as: regular?

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/hamming.rb', line 2

def hamming?
  smooth?(5) 
end

#happy?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/numb/happy.rb', line 3

def happy?
  return false unless positive?
  n = self
  sad = '4 16 37 58 89 145 42 20'
  seq = ""
  loop do
    n = n.digits.map{|d| d ** 2}.reduce(:+)
    seq << n.to_s  << ' '
    return true if n == 1
    return false if seq.include? sad   
  end
end

#harshad?Boolean Also known as: niven?, multidigital?

Returns:

  • (Boolean)


219
220
221
# File 'lib/numb/divisors.rb', line 219

def harshad?
  self >= 1 and (self % digital_sum).zero?
end

#heptagonal?Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/numb/figurate.rb', line 70

def heptagonal?
  n_gonal?(7)
end

#hexagonal?Boolean

Returns:

  • (Boolean)


74
75
76
77
# File 'lib/numb/figurate.rb', line 74

def hexagonal?
  return true if zero?
  ((Math.sqrt((8*self) + 1) + 1)/4).integer?
end

#highly_abundant?Boolean

Returns:

  • (Boolean)


33
34
35
36
# File 'lib/numb/divisors/abundant.rb', line 33

def highly_abundant?
  return true if self == 1
  (self - 1).downto(1).all?{|m| σ > m.σ }
end

#highly_composite?Boolean Also known as: julian?

Returns:

  • (Boolean)


171
172
173
174
175
# File 'lib/numb/divisors.rb', line 171

def highly_composite?
  return false if self > 6 and not (abundant? or primorial_product?)
  return true if [1,4,36].include?(self)
  minimal? and (self - 1).downto(1).all?{|n| τ > n.τ}
end

#hilbert?Boolean

Returns:

  • (Boolean)


3
4
5
6
# File 'lib/numb/hilbert.rb', line 3

def hilbert?
  return false unless positive?
  ((self - 1) % 4) == 0
end

#hoax?Boolean

Returns:

  • (Boolean)


226
227
228
229
# File 'lib/numb/divisors.rb', line 226

def hoax?
  return false unless composite?
  sum_of_digits == prime_factors.uniq.map{|f| f.sum_of_digits}.reduce(:+)
end

#hyperperfect?(k = 1) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


53
54
55
56
# File 'lib/numb/divisors/perfect.rb', line 53

def hyperperfect?(k=1)
  raise ArgumentError unless k >= 1
  (1 + (k * (σ - self - 1))) == self
end

#iban?Boolean Also known as: blind?

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/iban.rb', line 2

def iban?
  not words.include?('i')
end

#idempotent(k) ⇒ Object



3
4
5
# File 'lib/numb/idempotent.rb', line 3

def idempotent(k)
  (k.choose(self) * (self**(k - self))).to_i
end

#idoneal?Boolean Also known as: convenient?

Returns:

  • (Boolean)


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
# File 'lib/numb/idoneal.rb', line 2

def idoneal?
  n = self
  # Conjecture 2 (Euler) The largest idoneal number is n = 1848
  # Conjecture 5 (Gauss) If c(−4n) = 1, then n ≤ 1848.
  return false if n > 1848

  # Theorem 3 (Euler) 
  # 1. If n is an idoneal number which is a square, then n =  1, 4, 9, 16, or 25.
  return false if n.square? and ![1, 4, 9, 16, 25].include?(n)
  if n.divides?(4)
    n_over_4 = n/4

    # Theorem 12 (Grube)
    # (c) If n is idoneal and 4||n, then n = 4, 12, 28, 60
    return false if n_over_4.odd? and ![4,12,28,60].include?(n)
    
    # Theorem 12 (Grube)
    # If n is idoneal and 16|n, then n = 16, 48, 112, 240.
    if n.divides?(16)
      return [16, 48, 112, 240].include?(n)
    end

    # Theorem 3 (Euler) 
    # 6. If n ≡ 1 (mod 4) is idoneal and n != 1, then 4n is not idoneal.
    # 8. If n ≡ 8 (mod 16) is idoneal, then 4n is not idoneal.
    # 9. If n ≡ 16 (mod 32) is idoneal, then 4n is not idoneal.

    # Corollary 10 (Euler)
    # Thus, if n ≡ 0 (mod 32) or if n ≡ 4 (mod 16) and n > 4, then n is not idoneal.
    if n.modulo(32).zero? or n.modulo(16) == 4 and n > 4
      return false
    end
  end

  # Theorem 12 (Grube)
  # (a) If n is idoneal and 9|n, then n = 9, 18, 45, 72.
  return [9, 18, 45, 72].include?(n) if n.divides?(9)
  
  # Theorem 12 (Grube)
  # (b) If n is idoneal and 25|n, then n = 25.
  return n == 25 if n.divides?(25)
  
  # Corollary 8 
  # If n ≡ 3 (mod 4) is idoneal, then n = 3, 7 or 15.
  return [3, 7, 15].include?(n) if n.modulo(4) == 3
   
  # Perform a brute force test of whether n == ab + bc + ca; if it does, for
  # some distinct integer a, b, and c, n is not idoneal
  max = Math.sqrt(n/3)
  (1..max).each do |a|
    b_max = n - (a**2) - (a+1)**2 - (a+1)**2
    ((a+1)..b_max).each do |b|
      ab = a*b
      c_max = n - ab - b*(b+1)
      ((b+1)..c_max).each do |c|
        sum = ab + b*c + c*a
        return false if sum == n
        break if sum > n
      end
    end
  end
  true
end

#impolite?Boolean

Returns:

  • (Boolean)


114
115
116
# File 'lib/numb/divisors.rb', line 114

def impolite? 
  not polite?
end

#in_sequence?(args) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/numb/in_sequence.rb', line 3

def in_sequence?(args)
  args = {range: (1..self), cond: :<, initial: []}.merge(args)
  return true if Array(args[:initial]).include?(self)
  args[:range].each do |n|
    next if (term = n.send(args[:seq])).send(args[:cond], self)
    return term == self ? true : false
  end
end

#infinitary_divisorsObject



231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/numb/divisors.rb', line 231

def infinitary_divisors
  pf = Hash[prime_factors.uniq.map{|f| [f, 0]}]
  bin = divisors.map do |d|
    prime_divisors = pf.map(&:first)
    [d, pf.merge(Hash[d.primaries]).
      values.
      map{|v| sprintf("%.#{to_s(2).size}b", v)}.join]
  end
  bin = Hash[bin]
  target = bin[self].chars.map.with_index.to_a.select{|a,b| a == '0'}.map(&:last)
  bin.select{|d,b| target.all?{|i| b[i] == '0'}}.keys.sort
end

#infinitary_perfect?Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/numb/divisors/perfect.rb', line 70

def infinitary_perfect?
  σ∞ == 2*self
end

#integer?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/integer_p.rb', line 2

def integer?
  true
end

#interprime?Boolean

Returns:

  • (Boolean)


58
59
60
61
# File 'lib/numb/primes.rb', line 58

def interprime?
  return false if prime?
  self == (next_prime + prev_prime)/2
end

#isqrtObject



24
25
26
# File 'lib/numb.rb', line 24

def isqrt
  sqrt.floor
end

#jacobsthal_lucasObject



6
7
8
# File 'lib/numb/jacobsthal_lucas.rb', line 6

def jacobsthal_lucas
  lucas2(1, -2)
end

#jacobsthal_lucas?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/jacobsthal_lucas.rb', line 2

def jacobsthal_lucas?
  in_sequence?(seq: :jacobsthal_lucas, initial: 2)
end

#k_perfect?(k) ⇒ Boolean Also known as: multiply_perfect?

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/divisors/perfect.rb', line 3

def k_perfect?(k)
  σ == k * self
end

#kaprekar?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
11
12
13
# File 'lib/numb/kaprekar.rb', line 3

def kaprekar?
  return true if self == 1
  sdigits = (self ** 2).digits
  (1..sdigits.size-1).each do |first|
    a = sdigits.first(first).join.to_i
    b = sdigits.last(sdigits.size-first).join.to_i
    next if [a,b].any?{|n| n.zero?}
    return true if (a + b) == self
  end
  false
end

#keith?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
11
12
13
# File 'lib/numb/keith.rb', line 3

def keith?
  return false unless (n = self) > 9
  terms = n.to_s.split(//).map{|d| d.to_i}
  loop do
    return true if (n = terms.reduce(:+)) == self
    return false if n > self
    terms.shift
    terms << n
  end
  false
end

#knuthObject



3
4
5
6
7
# File 'lib/numb/knuth.rb', line 3

def knuth
  return 1 if zero?
  n = self - 1
  1 + [2 * (n/2).knuth, 3 * (n/3).knuth].min
end

#knuth?Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/numb/knuth.rb', line 9

def knuth?
  in_sequence?(range: downto(0), seq: :knuth, cond: :>)
end

#knödel?(k) ⇒ Boolean Also known as: knodel?

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/numb/knodel.rb', line 3

def knödel?(k)
  n = self
  return false unless n > k and composite?
  exp = n - k + 1
  (1...n).select{|j| j.coprime?(n)}.all? do |j|
    (j**exp - j).remainder(n).zero?
  end
end

#kynea?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
# File 'lib/numb/kynea.rb', line 3

def kynea?
  return true if self == 7
  a, b = to_s(2).match(/^(10+)(1+)$/).to_a[1..-1]
  return false if (a.nil? or b.nil?)
  a.length == (b.length - 1)
end

#lah(k) ⇒ Object



3
4
5
# File 'lib/numb/lah.rb', line 3

def lah(k)
  ((self-1).choose(k-1) * Rational(factorial, k.factorial)).to_i
end

#leonardo?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
# File 'lib/numb/leonardo.rb', line 2

def leonardo?
  n = self
  return 1 if n <= 1
  phi = Hash[[:+, :-].map{|sign| [sign, (1.send(sign, Math.sqrt(5)) / 2) ]}]
  divisor = phi[:+] - phi[:-]
  (1..n).any? do |m|
    sum = ((2 * ( ( phi[:+]**(m+1) - phi[:-]**(m+1) ).fdiv( divisor ) )) - 1)
    return false unless sum.finite?
    sum.floor == self
  end
end

#leyland?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
# File 'lib/numb/leyland.rb', line 2

def leyland?
  (2..sqrt).each do |x|
    (x..sqrt).each do |y|
      sum = x**y + y**x
      return true if sum == self
      break if sum > self
    end
  end
  false
end

#liouvilleObject



156
157
158
# File 'lib/numb/primes.rb', line 156

def liouville
  (-1)**Ω
end

#lucasObject



6
7
8
# File 'lib/numb/lucas.rb', line 6

def lucas
  lucas2(1, -1)
end

#lucas2(p, q) ⇒ Object

Raises:

  • (ArgumentError)


3
4
5
6
7
8
# File 'lib/numb/lucas2.rb', line 3

def lucas2(p, q)
  d = (p**2) - (4*q)
  raise ArgumentError unless d > 0
  d_root = d.sqrt
  (Rational(p + d_root, 2)**self + Rational(p - d_root, 2)**self).round
end

#lucas?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/lucas.rb', line 2

def lucas?
  in_sequence?(seq: :lucas, initial: [2])
end

#lucas_carmichael?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
# File 'lib/numb/lucas_carmichael.rb', line 2

def lucas_carmichael?
  return false unless composite? and odd? and square_free? 
  prime_factors.all? do |prime_factor|
    succ.divides?(prime_factor + 1)
  end
end

#lychrel?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
# File 'lib/numb/lychrel.rb', line 2

def lychrel?
  n = self
  # This limit is as arbitrary as it looks
  100.times do
    return false if n.palindrome?
    n += n.reverse
  end
  true
end

#mangoldtObject



174
175
176
# File 'lib/numb/primes.rb', line 174

def mangoldt
  prime? ? Math.log(prime_factors.first) : 0
end

#mersenne?Boolean Also known as: fermat_lucas?

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/mersenne.rb', line 2

def mersenne?
  zero? or repunit?(2)
end

#mersenne_prime?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/numb/primes.rb', line 63

def mersenne_prime?
  mersenne? and prime?
end

#mertensObject

TODO: Consider Deléglise and Rivat’s “Computing the Summation of the Mőbius Function”, Experimental Mathematics, Vol. 5 (1996), No. 4



14
15
16
# File 'lib/numb/mobius.rb', line 14

def mertens
  (1..self).map(&).reduce(:+)
end

#minimal?Boolean

Returns:

  • (Boolean)


383
384
385
# File 'lib/numb/divisors.rb', line 383

def minimal?
  τ.first_with_n_divisors == self
end

#mms_pair?(other) ⇒ Boolean Also known as: maris_mcgwire_sosa_pair?

Returns:

  • (Boolean)


3
4
5
6
7
8
9
# File 'lib/numb/mms_pair.rb', line 3

def mms_pair?(other)
  return false unless consecutive?(other)
  sum = [self,other].map do |n|
    (n.digits + n.prime_factors.map{|p| p.digits}.flatten).reduce(:+)
  end
  sum.first == sum.last
end

#mobiusObject Also known as: möbius, μ



3
4
5
6
# File 'lib/numb/mobius.rb', line 3

def mobius
 return if self < 1
 ω < Ω  ? 0 : liouville
end

#modulo_order(n) ⇒ Object Also known as: haupt_exponent, multiplicative_order



2
3
4
5
6
7
# File 'lib/numb/modulo_order.rb', line 2

def modulo_order(n)
  return 0 if n < 1
  return 1 if self == 2 and n == 1
  (1..n.totient).each{|e| return e if (self**e).modulo(n) == 1}
  0
end

#motzkinObject



3
4
5
6
7
# File 'lib/numb/motzkin.rb', line 3

def motzkin
  n = self
  return 1 if n <= 1
  ((3 * (n - 1) * (n - 2).motzkin) + (2 * n).succ * (n - 1).motzkin) / (n + 2)
end

#motzkin?Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
# File 'lib/numb/motzkin.rb', line 9

def motzkin?
  (1..self).each do |n|
    m = n.motzkin
    next if m < self
    return m == self ? true : false
  end
end

#multiamicable?(m, a, b) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
# File 'lib/numb/divisors/amicable.rb', line 3

def multiamicable?(m, a, b)
  return false unless m != self and m < self and a.positive? and b.positive?
  m.σ - m == a*self and σ - self == b*m
end

#myriagonal?Boolean

Returns:

  • (Boolean)


79
80
81
# File 'lib/numb/figurate.rb', line 79

def myriagonal?
  n_gonal?(10_000)
end

#ménageObject Also known as: menage



3
4
5
6
7
8
9
10
11
12
# File 'lib/numb/ménage.rb', line 3

def ménage
  return 1 if zero? # FIXME: Check this
  return 0 unless self > 1
  (0..self).map do |k|
    Rational(2 * self, 2 * self - k) * 
      ((2 * self) - k).choose(k) *
      (self - k).factorial *
      (-1)**k
  end.reduce(:+).to_i
end

#ménage?Boolean Also known as: menage?

Returns:

  • (Boolean)


14
15
16
17
18
19
# File 'lib/numb/ménage.rb', line 14

def ménage?
  (1..self).each do |n|
    next if (m = n.ménage) < self
    return m == self ? true : false
  end
end

#n_gonal?(n) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


60
61
62
63
64
# File 'lib/numb/figurate.rb', line 60

def n_gonal?(n)
  raise ArgumentError unless n.is_a?(Integer) and n >= 3
  return true if zero?
  ((Math.sqrt((8*n - 16)*self + (n-4)**2) + n - 4) / (2*n - 4)).integer?
end

#n_step_fibonacci(n) ⇒ Object



3
4
5
6
7
# File 'lib/numb/n_step_fibonacci.rb', line 3

def n_step_fibonacci(n)
  return 0 if self <= (n - 2) 
  return 1 if self <= (n - 1)
  (1..n).map{|i| (self-i).n_step_fibonacci(n) }.reduce(:+)
end

#narcissistic?Boolean Also known as: armstrong?, plus_perfect?

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/narcissistic.rb', line 3

def narcissistic?
  self == digits.map{|d| d ** digits.size}.reduce(:+)
end

#near_square?(k) ⇒ Boolean

Returns:

  • (Boolean)


83
84
85
# File 'lib/numb/figurate.rb', line 83

def near_square?(k)
  (self - k).square?
end

#next_primeObject



67
68
69
70
71
# File 'lib/numb/primes.rb', line 67

def next_prime
  p = succ
  p += 1 until p.prime?
  p
end

#nexus(d) ⇒ Object



3
4
5
# File 'lib/numb/nexus.rb', line 3

def nexus(d)
  (self + 1)**d.succ - self**d.succ
end

#nivenmorphic?Boolean Also known as: harshadmorphic?

Returns:

  • (Boolean)


3
4
5
6
7
# File 'lib/numb/nivenmorphic.rb', line 3

def nivenmorphic?
  return true if self == 0
  return false unless positive?
  niven? && to_s.end_with?(digital_sum.to_s)
end

#noncototient?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
# File 'lib/numb/noncototient.rb', line 3

def noncototient?
  return false if self < 10 or odd?
  (isqrt..(2 * self)).none? do |m|
    m.cototient == self
  end
end

#nonhypotenuse?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
# File 'lib/numb/nonhypotenuse.rb', line 2

def nonhypotenuse?
  # Shanks, Daniel Non-hypotenuse numbers. Fibonacci Quart. 13 (1975), no.
  # 4, 319-321.
  prime_factors.none?{|f| (f - 1).divides?(4) }
end

#nonzero_digitsObject



9
10
11
# File 'lib/numb/cyclic.rb', line 9

def nonzero_digits
  digits.reject(&:zero?)
end

#nswObject



3
4
5
6
7
8
9
# File 'lib/numb/nsw.rb', line 3

def nsw
  case self
    when 0 then 1
    when 1 then 7
    else        6 * (self - 1).nsw - (self - 2).nsw
  end
end

#nsw?Boolean

Returns:

  • (Boolean)


12
13
14
15
# File 'lib/numb/nsw.rb', line 12

def nsw?
  m = self
  (rhs = (m**2).succ).divides?(2) and 2 * ((rhs/2).isqrt**2) == rhs
end

#nth_primeObject Also known as: prime

Returns, after many eons, the nth prime, where n = self

Raises:

  • (ArgumentError)


109
110
111
112
113
114
115
116
# File 'lib/numb/primes.rb', line 109

def nth_prime
  n = self
  return 2 if n == 1
  raise ArgumentError if n < 1
  (2..( 2*n * Math.log(n) + 2).floor).map do |k|
    1 - (k.π.fdiv(n)).floor
  end.reduce(:+) + 2
end

#number_of_distinct_prime_factorsObject Also known as: omega, ω



143
144
145
# File 'lib/numb/primes.rb', line 143

def number_of_distinct_prime_factors
  prime_factors.uniq.size
end

#number_of_prime_factorsObject Also known as: bigomega, Ω, roundness



149
150
151
# File 'lib/numb/primes.rb', line 149

def number_of_prime_factors
  prime_factors.size
end

#oban?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/oban.rb', line 2

def oban?
  not words.include?(?o)
end

#octagonal?Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/numb/figurate.rb', line 87

def octagonal?
  n_gonal?(8)
end

#octahedralObject



96
97
98
# File 'lib/numb/figurate.rb', line 96

def octahedral
  (Rational(self, 3) * (2 * self**2 + 1)).to_i
end

#octahedral?Boolean

Returns:

  • (Boolean)


100
101
102
# File 'lib/numb/figurate.rb', line 100

def octahedral?
  in_sequence?(seq: :octahedral)
end

#odious?Boolean

Returns:

  • (Boolean)


2
3
4
5
# File 'lib/numb/odious.rb', line 2

def odious?
  return false unless positive?
  to_s(2).count('1').odd?
end

#ordinalObject



2
3
4
5
6
7
8
9
10
# File 'lib/numb/ordinal.rb', line 2

def ordinal
  case to_s
    when /^1\d$/ then 'th'
    when /1$/    then 'st'
    when /2$/    then 'nd'
    when /3$/    then 'rd'
    else              'th'
  end
end

#ore?Boolean Also known as: harmonic_divisor?

Returns:

  • (Boolean)


244
245
246
247
# File 'lib/numb/divisors.rb', line 244

def ore?
  div = divisors
  Rational(div.size, div.map{|d| d.reciprocal}.reduce(:+)).denominator == 1
end

#palindrome?(base = 10) ⇒ Boolean Also known as: palindromic?

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/palindrome.rb', line 3

def palindrome?(base=10)
  base(base) == base(base).reverse
end

#pandigital?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/pandigital.rb', line 3

def pandigital?
  (0..9).all?{|d| digits.include? d}
end

#parasitic?(n = nil) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
# File 'lib/numb/parasitic.rb', line 3

def parasitic?(n=nil)
  return (1..9).any?{|x| parasitic?(x)} if n.nil?
  return true if (n == 1 && self == 1)
  return false unless self > 9
  raise ArgumentError unless (n.positive? && n < 10)
  (n*self) == [digits.last, digits[0..-2]].join.to_i
end

#pell_lucasObject



6
7
8
# File 'lib/numb/pell_lucas.rb', line 6

def pell_lucas
  lucas2(2, -1)
end

#pell_lucas?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/pell_lucas.rb', line 2

def pell_lucas?
  in_sequence?(seq: :pell_lucas, initial: [2])
end

#pentagonal?Boolean

Returns:

  • (Boolean)


108
109
110
# File 'lib/numb/figurate.rb', line 108

def pentagonal?
  n_gonal?(5)
end

#pentatopeObject



112
113
114
# File 'lib/numb/figurate.rb', line 112

def pentatope
  (Rational(tetrahedral, 4) * (self + 3)).to_i
end

#perfect?Boolean

Returns:

  • (Boolean)


9
10
11
12
13
# File 'lib/numb/divisors/perfect.rb', line 9

def perfect?
  return false if self < 6 or self.odd? or self.to_s !~ /(6|8)$/
  return false if self != 6 and digital_root != 1  
  k_perfect?(2)
end

#perfect_powerObject



317
318
319
320
321
322
# File 'lib/numb/divisors.rb', line 317

def perfect_power
  return 1 if (n = self) <= 1
  this = (n - 1).perfect_power.succ
  this += 1 while (this.prime? or not this.perfect_power?)
  this
end

#perfect_power?Boolean

Returns:

  • (Boolean)


49
50
51
52
53
54
# File 'lib/numb/divisors.rb', line 49

def perfect_power?
  return false unless positive?
  return true if self == 1
  divisors = self.divisors
  (2..Math.log2(self)).any? { |pow| divisors.any? {|div| (div ** pow) == self} } 
end

#perrin?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
# File 'lib/numb/perrin.rb', line 2

def perrin?
  return true if (perin = [3, 0, 2]).include?(self)
  until perin.last > self
    perin << perin[-2] + perin[-3]
    return true if perin.last == self
  end
  false
end

#persistent?(n) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/persistent.rb', line 3

def persistent?(n)
  (1..n).all?{|x| (x * self).pandigital?}
end

#placesObject



29
30
31
32
33
34
35
36
# File 'lib/numb/words.rb', line 29

def places
  n = self
  {trillions: 10e11, billions: 10e8, millions: 10e5, thousands: 10e2, 
   hundreds: 10e1, tens: 10, units: 1}.map do |k,v| 
    v, n = n.divmod(v)
    [k, v]
   end.tap{|a| return Hash[a] }
end

#polite?Boolean

Returns:

  • (Boolean)


118
119
120
121
# File 'lib/numb/divisors.rb', line 118

def polite? 
  return true if self == 1
  politeness.positive?
end

#politenessObject



110
111
112
# File 'lib/numb/divisors.rb', line 110

def politeness
  divisors.select{|d| d > 1}.select{|d| d.odd?}.size
end

#polydivisible?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
# File 'lib/numb/polydivisible.rb', line 3

def polydivisible?
  return true if self == 1
  return false if digits.first == 0
  1.upto(digits.size).all? do |first|
    (digits.first(first).join.to_i % first) == 0
  end
end

#positive?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/positive.rb', line 2

def positive?
  self > 0
end

#poulet?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/poulet.rb', line 2

def poulet?
  fermat_pseudoprime? 2
end

#powerful?Boolean Also known as: handsome?

Returns:

  • (Boolean)


29
30
31
32
33
# File 'lib/numb/divisors.rb', line 29

def powerful?
  return false unless positive?
  divisors = self.divisors
  divisors.select {|d| d.prime? }.all?{|prime| divisors.include? (prime ** 2)}
end

#practical?Boolean

Implementation of Stewart, B. M. (1954), “Sums of distinct divisors”, American Journal of Mathematics 76: 779–785, doi:10.2307/2372651, MR0064800

Returns:

  • (Boolean)


254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/numb/divisors.rb', line 254

def practical?
  sum = 1
  k = 2
  n = self
  while (n >= k)
    s = 1
    u = 0
    while (n % k == 0)
      n = n/k
      s = s * k + 1
      u += 1
    end
    unless (u == 0)
      return false if (k > sum + 1)
      sum *= s
    end
    k += (k == 2) ? 1 : 2
  end
  true
end

#prev_primeObject



73
74
75
76
77
# File 'lib/numb/primes.rb', line 73

def prev_prime
  p = self - 1
  p -= 1 until p.prime?
  p
end

#prime_factorsObject



160
161
162
163
# File 'lib/numb/primes.rb', line 160

def prime_factors
  return [] if zero?
  prime_division.map{|pair| [pair.first] * pair.last}.flatten
end

#prime_power?(k = nil) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/prime_power.rb', line 3

def prime_power?(k=nil)
  self == 1 or (primaries.size == 1 and (not k or primaries.first.last == k))
end

#prime_signatureObject



101
102
103
# File 'lib/numb/primes.rb', line 101

def prime_signature
  prime_division.map{|base, exponent| exponent}.sort.reverse
end

#primitive_abundant?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/numb/divisors/abundant.rb', line 38

def primitive_abundant?
  abundant? and proper_divisors.all?(&:deficient?)
end

#primitive_pseudoperfect?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/numb/divisors/perfect.rb', line 66

def primitive_pseudoperfect?
  pseudoperfect? and proper_divisors.sort.none?(&:pseudoperfect?)
end

#primitive_root?(g = nil) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/numb/primitive_root.rb', line 2

def primitive_root?(g=nil)
  if g
    return true if g.zero? and self == 1
    coprime?(g) and g.modulo_order(self) == totient
  else
    return true if [1, 2, 4].include?(self)
    prime_factors.select(&:odd?).any? do |p|
      [1,2].any? do |x|
        Math.log(self / x, p).integer?
      end
    end
  end
end

#primitive_rootsObject



2
3
4
5
# File 'lib/numb/primitive_roots.rb', line 2

def primitive_roots
  return [] unless primitive_root?
  (0..self).select{|n| primitive_root?(n)}
end

#primorialObject



17
18
19
20
21
# File 'lib/numb/primorial.rb', line 17

def primorial
  return nil if self < 1
  return 1 if self == 1
  (prime? ? self : prev_prime).downto(2).select(&:prime?).reduce(:*)
end

#primorial?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
# File 'lib/numb/primorial.rb', line 3

def primorial?
  return true if self == 1
  pd = prime_division
  (pd.map{|b,e| e}.uniq == [1]) and (pd.map{|b,e| b} == Prime.first(pd.size))
end

#primorial_product?Boolean

Returns:

  • (Boolean)


9
10
11
12
13
14
15
# File 'lib/numb/primorial.rb', line 9

def primorial_product?
  return true if primorial?
  return false if prime?
  divisors.each_slice(2).
           reject{|pair| pair == [1, self]}.
           any?{|pair| pair.all?(&:primorial_product?)} 
end

#pronic?Boolean Also known as: heteromecic?, oblong?, promic?

Returns:

  • (Boolean)


2
3
4
5
# File 'lib/numb/pronic.rb', line 2

def pronic?
  return false unless even? and (positive? or zero?)
  (Math.sqrt(succ).round - sqrt.round) == 1
end

#proper_divisorsObject



123
124
125
# File 'lib/numb/divisors.rb', line 123

def proper_divisors
  divisors.reject {|d| d == self }
end

#propertiesObject



2
3
4
5
6
7
8
9
10
# File 'lib/numb/properties.rb', line 2

def properties
  methods.grep(/\?/).
          map{|m| method(m)}.
          uniq. # Filter out aliases
          select{|m| m.arity.zero? and m[]}.
          map{|m| m.name[0..-2]}. # Strip question mark
          map(&:to_sym).
          sort
end

#proth?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
# File 'lib/numb/proth.rb', line 2

def proth?
  return false if self < 3
  n_max = Math.log2(self-1).ceil
  (1..(self / n_max)).select{|k| k.odd?}.any? do |k|
    (1..n_max).select{|n| 2**n > k}.any? do |n|
      break if (x = (k * (2**n)) + 1) > self 
      x == self
    end
  end
end

#pyramidal(r) ⇒ Object



91
92
93
94
# File 'lib/numb/figurate.rb', line 91

def pyramidal(r)
  n = self
  (6.reciprocal * n * n.succ * (((r - 2) * n) + (5 - r))).to_i
end

#qObject



3
4
5
6
# File 'lib/numb/q.rb', line 3

def q
  return 1 if (n = self) <= 2
  (n - (n - 1).q).q + (n - (n - 2).q).q
end

#q?Boolean

Returns:

  • (Boolean)


10
11
12
# File 'lib/numb/q.rb', line 10

def q?
  (1..(self ** 2)).any?{|n| n.q == self} or nil
end

#quadratic_residue?(p) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/reciprocity.rb', line 3

def quadratic_residue?(p)
  residue? p, 2
end

#quarticfree?Boolean Also known as: biquadratefree?

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/quarticfree.rb', line 2

def quarticfree?
  self == 1 or prime_signature.max < 4
end

#ramanujan_tauObject



419
420
421
422
423
424
# File 'lib/numb/divisors.rb', line 419

def ramanujan_tau
  return 1 if (n = self) == 1
  n**4 * n.σ - 24 * (1...n).map do |k|
    k**2 * (35 * k**2 - 52 * k * n + 18 * n**2) * k.σ * (n-k).σ
  end.reduce(:+)
end

#reciprocalObject



11
12
13
# File 'lib/numb/reciprocity.rb', line 11

def reciprocal
  self ** -1
end

#refactorable?Boolean Also known as: tau?

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/refactorable.rb', line 3

def refactorable?
  divides?(τ)
end

#repunitObject



6
7
8
# File 'lib/numb/repunit.rb', line 6

def repunit
  (10 ** self) / 9 
end

#repunit?(base) ⇒ Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/repunit.rb', line 2

def repunit?(base)
  !!to_s(base).match(/^1+$/)
end

#reverseObject



2
3
4
# File 'lib/numb/reverse.rb', line 2

def reverse
  to_s.reverse.to_i
end

#rhonda?(base = 10) ⇒ Boolean

Returns:

  • (Boolean)


275
276
277
278
# File 'lib/numb/divisors.rb', line 275

def rhonda?(base=10)
  d = base == 10 ? digits : to_s(base).split(//).map{|_| _.to_i(base)} 
  d.reduce(:*) == base * (prime_factors.reduce(:+) || 0)
end

#rough?(k) ⇒ Boolean

Returns:

  • (Boolean)


289
290
291
# File 'lib/numb/divisors.rb', line 289

def rough?(k)
  prime_factors.all?{|f| f >= k}
end

#rulerObject



391
392
393
# File 'lib/numb/divisors.rb', line 391

def ruler
  (2 * self).primaries.first.last
end

#safe_prime?Boolean

Returns:

  • (Boolean)


124
125
126
# File 'lib/numb/primes.rb', line 124

def safe_prime?
  prime? and odd? and ((self - 1) / 2).prime?
end

#schröderObject Also known as: schroder



3
4
5
6
7
8
9
# File 'lib/numb/schröder.rb', line 3

def schröder
  return 1 if zero?
  n = self
  (n-1).schröder + (0...n).map do |k| 
    k.schröder * (n - 1 - k).schröder
  end.reduce(:+)
end

#schröder?Boolean Also known as: schroder?

Returns:

  • (Boolean)


15
16
17
# File 'lib/numb/schröder.rb', line 15

def schröder?
  in_sequence?(seq: :schröder, initial: 1)
end

#segmentedObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/numb/segmented.rb', line 3

def segmented
  return self if self <= 2
  this = ((n = self)-1).segmented.succ

  sum = Hash.new{|h, k| h[k] = k.map(&:segmented).reduce(:+) }
  
  priors_sum = ->(target) do
    (n - 2).downto(1).any? do |start|
      (start.succ..(n-1)).any? do |stop|
        break if (s = sum[ start..stop ]) > target
        s == target
      end
    end
  end

  this += 1 while priors_sum[ this ]
  this
end

#segmented?Boolean Also known as: prime_number_of_measurement?

Returns:

  • (Boolean)


24
25
26
# File 'lib/numb/segmented.rb', line 24

def segmented?
  in_sequence?(seq: :segmented)
end

#self?Boolean Also known as: colombian?, devlai?

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/numb/self.rb', line 3

def self?
  # Formula from: Kaprekar, D. R. The Mathematics of New Self-Numbers
  #  Devaiali (1963): 19 - 20
  dr_star = digital_root.odd? ? (digital_root + 9) / 2 : digital_root / 2
  0.upto(digits.size).none? do |i|
    (self - dr_star - 9 * i) + (self - dr_star - 9 * i).sod == self
  end
end

#self_descriptive?(base = 10) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
# File 'lib/numb/self_descriptive.rb', line 3

def self_descriptive?(base=10)
  dig = digits
  return false unless digits.size == base
  dig.each_with_index{|d,i| return false unless dig.count(i) == d}
  true
end

#semiperfect?Boolean Also known as: pseudoperfect?

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/numb/divisors/perfect.rb', line 15

def semiperfect?
 return false if deficient?
 return true if perfect?
 possibles = { 0 => true}
 proper_sod = (sod = σ || 0) - self
 proper_divisors.reverse.each do |divisor|
   possibles.keys.each do |possible|
     possibles.delete(possible) if possible + sod < self 
     x = possible + divisor
     return true if x == self or x == proper_sod 
     possibles[x] = true if x < self        
   end
   sod -= divisor
 end
 false
end

#semiprime?Boolean

Returns:

  • (Boolean)


128
129
130
# File 'lib/numb/primes.rb', line 128

def semiprime?
  Ω == 2
end

#singly_even?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/singly_even.rb', line 2

def singly_even?
  modulo(4) == 2
end

#smarandacheObject



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/numb/divisors.rb', line 395

def smarandache
  if    self == 1                       then 1
  elsif prime?                          then self
  elsif factorial?                      then factorial_of?
  elsif primaries.map(&:last).uniq == 1 then primaries.last.first
  elsif primaries.size == 1
    p, k = primaries.first
    return p*k if k < p
    i = k/p
    loop do
      sum = i
      r = i / p
      while r > 0
        sum += r
        r /= p
      end
      return i*p if sum >= k
      i += 1
    end
  else
    primaries.map{|b,e| (b**e).smarandache}.max
  end
end

#smarandache_wellin?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/numb/smarandache_wellin.rb', line 3

def smarandache_wellin?
  prime_str = ''
  Prime.each do |prime|
    prime_str << prime.to_s
    return true if prime_str == to_s
    return false if prime_str.length >= to_s.length
  end
end

#smith?Boolean

Returns:

  • (Boolean)


280
281
282
283
# File 'lib/numb/divisors.rb', line 280

def smith?
  return false if prime?
  digital_sum == primaries.map{|d,e| d.digital_sum * e}.reduce(:+)
end

#smooth?(b) ⇒ Boolean

Returns:

  • (Boolean)


285
286
287
# File 'lib/numb/divisors.rb', line 285

def smooth?(b)
  prime_factors.none?{|f| f > b}
end

#sociable?(t) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
17
# File 'lib/numb/divisors/aliquot.rb', line 14

def sociable?(t)
  return false unless t >= 3
  aliquot_sequence(t.succ).last == self
end

#sophie_germain_prime?Boolean

Returns:

  • (Boolean)


120
121
122
# File 'lib/numb/primes.rb', line 120

def sophie_germain_prime?
  prime? and (2*self).succ.prime?
end

#sphenic?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/sphenic.rb', line 3

def sphenic?
  prime_signature == [1, 1, 1]
end

#sqrtObject



20
21
22
# File 'lib/numb.rb', line 20

def sqrt
  Math.sqrt(self)
end

#square?Boolean

Returns:

  • (Boolean)


3
4
5
6
# File 'lib/numb/figurate.rb', line 3

def square?
  return false unless zero? or (positive? and to_s(16)[-1] =~ /[0149]/)
  (sq = sqrt).finite? ? sq.integer? : nil
end

#square_free?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/numb/figurate.rb', line 16

def square_free?
   not μ.zero?
end

#square_partObject



387
388
389
# File 'lib/numb/divisors.rb', line 387

def square_part
  divisors.sort.reverse.each{|d| return d if d.square?}
end

#square_triangular?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/numb/figurate.rb', line 8

def square_triangular?
  square? and triangular?
end

#squared_triangular?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/numb/figurate.rb', line 12

def squared_triangular?
  square? and sqrt.to_i.triangular?
end

#starObject



116
117
118
# File 'lib/numb/figurate.rb', line 116

def star
  6 * self * (self - 1) + 1
end

#star?Boolean

Returns:

  • (Boolean)


120
121
122
123
124
125
# File 'lib/numb/figurate.rb', line 120

def star?
  return true if self == 1
  return false unless [1, 4].include?(digital_root) and 
    to_s.end_with?(*%w{01 13 21 33 37 41 53 61 73 81 93})
  centered_n_gonal?(12)
end

#stella_octangulaObject



131
132
133
# File 'lib/numb/figurate.rb', line 131

def stella_octangula
  octahedral + 8 * (self - 1).tetrahedral
end

#stella_octangula?Boolean

Returns:

  • (Boolean)


135
136
137
# File 'lib/numb/figurate.rb', line 135

def stella_octangula?
  in_sequence?(seq: :stella_octangula)
end

#stirling(m) ⇒ Object



3
4
5
6
7
8
# File 'lib/numb/stirling.rb', line 3

def stirling(m)
  n = self
  return 1 if (n.zero? and m.zero?) or m == n 
  return 0 if m > n or m.zero? or n.zero?
  (n-1).stirling(m-1) - (n-1)*(n-1).stirling(m)
end

#stirling2(m) ⇒ Object



3
4
5
6
7
8
# File 'lib/numb/stirling2.rb', line 3

def stirling2(m)
  n = self
  return 1 if (n.zero? and m.zero?) or m == n 
  return 0 if m > n or m.zero? or n.zero?
  (n-1).stirling2(m-1) + m * (n-1).stirling2(m)
end

#strictly_non_palindromic?Boolean

Returns:

  • (Boolean)


2
3
4
5
# File 'lib/numb/strictly_non_palindromic.rb', line 2

def strictly_non_palindromic?
  return true if (0..4).include?(self) or self == 6
  prime? and (2..isqrt).none?{|base| palindrome?(base)}
end

#størmer?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/størmer.rb', line 3

def størmer?
  ((self ** 2) + 1).prime_factors.max >= 2 * self
end

#subfactorialObject Also known as: derangements



2
3
4
# File 'lib/numb/subfactorial.rb', line 2

def subfactorial
  zero? ? 1 : self * (self - 1).subfactorial + (-1)**self
end

#sublime?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/numb/divisors/perfect.rb', line 62

def sublime?
  number_of_divisors.perfect? and σ.perfect?
end

#sum_of_divisors(k = 1) ⇒ Object Also known as: σ



135
136
137
# File 'lib/numb/divisors.rb', line 135

def sum_of_divisors(k=1)
  (k == 1 ? divisors : divisors.map{|d| d**k}).reduce(:+)
end

#sum_of_squaresObject

Raises:

  • (ArgumentError)


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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/numb/sum_of_squares.rb', line 14

def sum_of_squares
  n = self
  raise ArgumentError if n < 0
  return [0, 0, 0, n] if n <= 1

  decompose_prime = ->(p) do
    raise ArgumentError unless p.prime? and p.modulo(4) == 1
    b = 2
    unless p.modulo(8) == 5
      b = 3
      b = b.next_prime while (b**((p-1)/2)).modulo(p) == 1
    end
    b = (b**((p-1)/4)).modulo(p)
    a = p
    a, b = b, a.modulo(b) while (b**2) > p
    [b, a.modulo(b)]
  end
  
  isqrt = ->(i) do
    s = Math.sqrt(i).to_i
    [s, i - s * s]
  end
  
  # Pad return Array with leading zeroes so result is the sum of exactly 4
  # squares
  zero_pad = ->(l) { l + ([0] * (4 - l.size)) }
  
  # Remove powers of 4
  v = 1                 
  while (n & 3).zero?    
    n >>= 2             
    v += v
  end

  sort_scaled = ->(l) { l.sort.map{|x| v * x}}
  
  sq, p = isqrt[n]
  # n is a squarei; return its square root
  return [0, 0, 0, v * sq] if p.zero?
  
  # n is prime, n % 4 = 1
  # otherwise n was not a prime
  return sort_scaled[zero_pad[decompose_prime[n]]] if (n & 3 == 1) and n.prime?
  
  delta = 0
  if  n & 7 == 7   # Need 4 squares, subtract largest square delta^2
                   # such that (n > delta^2) and (delta^2 % 8 != 0)
    delta, n = sq, p
    
    if  (sq & 3).zero?
      delta -= 1
      n += delta + delta + 1
    end
    # sq % 4  = 0 -> delta % 8 in [3, 7]       ->
    # delta^2 % 8 = 1     -> n % 8 = 6
    # sq % 4 != 0 -> delta % 8 in [1, 2, 3, 5, 6, 7] ->
    # delta^2 % 8 in [1, 4] -> n % 8 in [3, 6]
    # and this implies n % 4 != 1, i.e. n cannot be a sum of two squares
    sq, p = isqrt[n]
    # sq^2 != n since n % 4 = 3 which is never true for a square
  end

  # This implies that n is a sum of three squares - now check whether n
  # is one of the special cases the rest of the algorithm could not handle.
  # Retrieve pre-computed result and scale with v
  return sort_scaled[zero_pad[[delta] + SPECIAL_DECOMP[n]]] if SPECIAL_DECOMP.key?(n)

  # Now perform search distinguishing two cases noting that n % 4 != 0
  # Case 1: n % 4 = 3, n = x^2 + 2*p, p % 4 = 1,
  # p prime, p = y^2 + z^2 implies n = x^2 + (y + z)^2 + (y - z)^2
  if  n & 3 == 3
    if (sq & 1).zero?
      sq -= 1
      p += sq + sq + 1
    end
    p >>= 1
    loop do
      if  p.prime?
        r0, r1 = decompose_prime[p]
        return sort_scaled[[delta, sq, r0 + r1, (r0 - r1).abs]]
      end
      sq -= 2             # Next sq

      raise RuntimeError if sq < 0
      p += sq + sq + 2        # Next p
    end
  end
  # Case 2: n % 4 = 1 or n % 4 = 2, n = x^2 + p,
  # p % 4 = 1, p prime, p = y^2 + z^2 implies n = x^2 + y^2 + z^2
  if  ((n - sq) & 1).zero?
    sq -= 1
    p += sq + sq + 1
  end

  loop do
    return sort_scaled[[delta, sq] + decompose_prime[p]] if p.prime?
    sq -= 2               # Next sq

    raise RuntimeError if sq < 0
    p += 4 * (sq + 1)         # Next p
  end
end

#sum_of_unitary_divisorsObject



167
168
169
# File 'lib/numb/divisors.rb', line 167

def sum_of_unitary_divisors
  divisors.select{|d| unitary_divisor?(d)}.reduce(:+) or 0
end

#super_catalanObject



3
4
5
6
7
8
9
10
# File 'lib/numb/super_catalan.rb', line 3

def super_catalan
  n = self
  return 1 if n <= 2
  Rational(
    3 * ((2 * n) - 3) * (n - 1).super_catalan - (n - 3) * (n - 2).super_catalan,
    n
  ).to_i
end

#super_catalan?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/numb/super_catalan.rb', line 14

def super_catalan?
  in_sequence?(seq: :super_catalan)
end

#super_d?(d) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/super_d.rb', line 3

def super_d?(d)
  (d * self**d).to_s.include?(d.to_s * d)
end

#super_poulet?Boolean

Returns:

  • (Boolean)


293
294
295
# File 'lib/numb/divisors.rb', line 293

def super_poulet?
  poulet? and divisors.all?{|d|  ((2**d) - 2).divides?(d)}
end

#superabundant?Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/numb/divisors/abundant.rb', line 42

def superabundant?
  return true if self == 1
  # Constraints due to "Abundant Numbers and the Riemann Hypothesis",
  # Briggs, 2006, Experimental Mathematics, vol. 15, no. 2
  ex = primaries.map(&:last)
  return false unless [ex.last, ex.first] == ex.minmax
  primaries[1..-1].all? do |b, e|
    (e - (ex[0] * Math.log(b, primaries[0][0])).floor <= 1) and e < 2**(ex[0] + 2)
  end or return false
  return false unless [4, 36].include?(self) or ex.last == 1
  1.upto(self - 1).all? do |m|
    m.abundancy < abundancy
  end
end

#superperfect?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/numb/divisors/perfect.rb', line 58

def superperfect?
  σ.σ == 2 * self
end

#takeuchiObject



3
4
5
6
7
8
9
10
11
# File 'lib/numb/takeuchi.rb', line 3

def takeuchi
  n = self
  return n if n <= 1
  (0..n-2).map do |k|
    (
      (2 * (n + k - 1).choose(k)) - (n + k).choose(k)
    ) * (n - k - 1).takeuchi
  end.reduce(:+) + (1..n).map(&:catalan).reduce(:+)
end

#takeuchi?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/numb/takeuchi.rb', line 15

def takeuchi?
  in_sequence?(seq: :takeuchi)
end

#tetrahedralObject



127
128
129
# File 'lib/numb/figurate.rb', line 127

def tetrahedral
  pyramidal(3)
end

#triangular?Boolean

Returns:

  • (Boolean)


104
105
106
# File 'lib/numb/figurate.rb', line 104

def triangular?
  n_gonal?(3)
end

#trimorphic?Boolean

Returns:

  • (Boolean)


3
4
5
# File 'lib/numb/trimorphic.rb', line 3

def trimorphic?
  (self ** 3).to_s.end_with? self.to_s
end

#twin_prime?(p) ⇒ Boolean

Returns:

  • (Boolean)


136
137
138
# File 'lib/numb/primes.rb', line 136

def twin_prime?(p)
  [p, self].all?(&:prime?) and p == self + 2
end

#uban?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/uban.rb', line 2

def uban?
  not words.include?(?u)
end

#undulating?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
# File 'lib/numb/undulating.rb', line 3

def undulating?
  dig = digits
  return false unless digits.size >= 3 and digits[0] != digits[1]
  dig.each_with_index do |d,i| 
    return false unless i.odd? ? d == dig[1] : d == dig[0]
  end
  true
end

#unhappy?Boolean Also known as: sad?

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/unhappy.rb', line 2

def unhappy?
  not happy?
end

#unitary_amicable?(n) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
# File 'lib/numb/divisors/amicable.rb', line 32

def unitary_amicable?(n)
  [n + self, sum_of_unitary_divisors].all? do |other|
    other == n.sum_of_unitary_divisors
  end
end

#unitary_divisor?(x) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/numb/divisors.rb', line 25

def unitary_divisor?(x)
  x.coprime?(self/x)
end

#unitary_perfect?Boolean

Returns:

  • (Boolean)


47
48
49
50
51
# File 'lib/numb/divisors/perfect.rb', line 47

def unitary_perfect?
  proper_divisors.select do |divisor|
    unitary_divisor?(divisor)
  end.reduce(:+) == self
end

#unitary_sociable?(t) ⇒ Boolean

Returns:

  • (Boolean)


19
20
21
22
23
# File 'lib/numb/divisors/aliquot.rb', line 19

def unitary_sociable?(t)
  return false unless t >= 3
  seq = aliquot_sequence(t.succ, ->(n){ n.sum_of_unitary_divisors - n})
  seq.size - 1  == t and seq.last == self
end

#untouchable?Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
# File 'lib/numb/divisors.rb', line 13

def untouchable?
  # * The first untouchable integer is 2
  # * Perfect numbers are never untouchable because they can be expressed
  #   as the sum of their own proper divisors
  # * If p is prime, the sum of the proper divisors of p**2 is p + 1;
  #   therefore, no untouchable number is one more than a prime.
  return false if self < 2 or perfect? or (self - 1).prime?
  (1..((self - 1)**2)).none? do |m|
    m.σ - m == self
  end
end

#unusual?Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/numb/divisors.rb', line 9

def unusual?
  prime_factors.max > sqrt
end

#vampire?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
9
10
11
# File 'lib/numb/vampire.rb', line 3

def vampire?
  return false unless composite? and digits.size.even?
  seen = {}
  digits.permutation.any? do |perm|
    fangs = [:first,:last].map {|pos| perm.send(pos,(digits.size/2)).join.to_i }.sort
    next if seen.key?(fangs)
    seen[fangs] = fangs.reduce(:*) == self
  end
end

#weird?Boolean

Returns:

  • (Boolean)


3
4
5
6
7
# File 'lib/numb/divisors.rb', line 3

def weird?
  return false unless positive?
  return false if odd? && self < (10 ** 17)
  not semiperfect? and abundant?
end

#wieferich_prime?Boolean

Returns:

  • (Boolean)


165
166
167
168
# File 'lib/numb/primes.rb', line 165

def wieferich_prime?
  return false unless prime?
  (2**(self - 1)).modulo(self ** 2) == 1
end

#woodall?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
# File 'lib/numb/woodall.rb', line 2

def woodall?
  x = succ
  divisors = x.square? ? x.divisors[0..-2] : x.divisors
  divisors.each_slice(2).any?{|a, b| a == Math.log2(b)}
end

#wordsObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/numb/words.rb', line 12

def words
  return WORDS[0] if zero?
  str = (place = places.to_a).map do |name, v|
    next if v.zero?
    case name
      when :units then WORDS[v]
      when :tens
        units = place.pop.last
        v == 1 ? WORDS[10 + units] 
               : WORDS[10 * v] + (units.zero? ? '' : ' ' + units.words)
      else
        v.words + ' ' + name.to_s[0..-2]
    end
  end.compact.join(', ')
  str.include?(',') ? str.sub(/,([^,]+)$/,' and\1') : str
end

#zeisel?Boolean

Returns:

  • (Boolean)


2
3
4
5
6
7
8
9
10
11
12
# File 'lib/numb/zeisel.rb', line 2

def zeisel?
  return false unless square_free? and (p=prime_factors.sort.uniq).size >= 3
  p.unshift(1)
  (1..p.max).any? do |a|
    b = p[1] - (a*p[0])
    p.each_with_index.all? do |n, i|
      next true if i.zero?
      n == (a*p[i-1]) + b
    end
  end
end

#zerofree?Boolean

Returns:

  • (Boolean)


2
3
4
# File 'lib/numb/zerofree.rb', line 2

def zerofree?
  not to_s.include?('0')
end

#πObject Also known as: prime_pi, prime_count

Returns the number of primes equal to or less than self



91
92
93
94
95
96
97
# File 'lib/numb/primes.rb', line 91

def π
  x = self
  return 0 if x == 1
  @prime_count ||= ([2] + (3..x).select(&:odd?)).map do |j|
    1 + ( ((2 - j.τ)/j).floor ).floor
  end.reduce(:+)
end

#σeObject Also known as: sum_of_e_divisors



152
153
154
155
156
# File 'lib/numb/divisors.rb', line 152

def σe
  # TODO: If squarefree, the sum of a number’s e-divisors is the number
  # itself. Do we gain anything significant by special-casing this?
  e_divisors.reduce :+
end

#σ∞Object Also known as: sum_of_infinitary_divisors, isigma



160
161
162
# File 'lib/numb/divisors.rb', line 160

def σ∞
  infinitary_divisors.reduce :+
end

#τObject Also known as: number_of_divisors, d

Returns the number of divisors of self



301
302
303
304
305
306
307
308
309
310
311
# File 'lib/numb/divisors.rb', line 301

def τ 
  # TODO: Consider something simpler, and perhaps faster, like
  # primaries.map(&:last).map(&:succ).reduce(:*)
  n = self
  return @nod if defined?(@nod)
  @nod = (1..isqrt).
    map {|i|  n.quo(i).to_i - (n - 1).quo(i).to_i }.
    reduce(:+) * 2
  @nod -= 1 if square?
  @nod
end

#φObject Also known as: totient



3
4
5
6
7
# File 'lib/numb/totient.rb', line 3

def φ
  return 1 if self == 1
  return self - 1 if prime?
  (prime_factors.uniq.map{|f| 1 - f.reciprocal}.reduce(:*) * self).to_i
end