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/ord.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/inrt.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/inv_mod.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/kronecker.rb,
lib/numb/parasitic.rb,
lib/numb/power_mod.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



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

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
38
39
40
# File 'lib/numb/divisors/perfect.rb', line 34

def almost_perfect?
  return true if self == 1
  # TODO: All known almost perfect numbers are powers of 2. If self
  # is within the range of integers thus tested, a power_of?(2) test
  # would avoid the need to factorise.
  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) {|Integer| ... } ⇒ Enumerator

An enumeration of numbers coprime to ‘x` from `self` onward. If a block is given, it is yielded to with the next number in the sequence; otherwise, an `Enumerator` is returned.

4.coprime(3).first(5) #=> [4, 5, 7, 8, 10]

Parameters:

  • x (Integer)

    each number in the enumeration is coprime with ‘x`

Yields:

  • (Integer)

    n next number that is >= ‘self` and coprime with `x`

Returns:

  • (Enumerator)

    returned if the block is omitted



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

def coprime(x)
  return enum_for(__method__, x) unless block_given?
  (self..Float::INFINITY).each do |n|
    yield n if n.coprime?(x)
  end
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)


195
196
197
# File 'lib/numb/divisors.rb', line 195

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)


94
95
96
97
# File 'lib/numb/divisors.rb', line 94

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)


164
165
166
# File 'lib/numb/divisors.rb', line 164

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

#divisorsObject



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

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

def dudeney?
  digits.reduce(:+) ** 3 == self
end

#e_divisorsObject



101
102
103
104
105
106
107
108
# File 'lib/numb/divisors.rb', line 101

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)


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

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)


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

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)


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

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

#exceptional?Boolean

Returns:

  • (Boolean)


453
454
455
# File 'lib/numb/divisors.rb', line 453

def exceptional?
  not ordinary?
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)


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

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



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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/numb/divisors.rb', line 341

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| 
        d = begin
          max_exponent = Math.log(limit, b).floor
          div.reject{|d| d > max_exponent}
        rescue FloatDomainError
          div
        end.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)


229
230
231
232
233
# File 'lib/numb/divisors.rb', line 229

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)


235
236
237
# File 'lib/numb/divisors.rb', line 235

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)


187
188
189
190
191
# File 'lib/numb/divisors.rb', line 187

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)


242
243
244
245
# File 'lib/numb/divisors.rb', line 242

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)


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

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)


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

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



247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/numb/divisors.rb', line 247

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)


73
74
75
# File 'lib/numb/divisors/perfect.rb', line 73

def infinitary_perfect?
  σ∞ == 2*self
end

#inrt(n) ⇒ Integer

Returns the integer ‘n`’th root of the absolute value of ‘self`.

(0..12).map{|n| (4**n).inrt(3)}
#=> [1, 1, 2, 4, 6, 10, 16, 25, 40, 64, 101, 161, 256]

Parameters:

  • n (Integer)

    root to take of ‘self`

Returns:

  • (Integer)

    The ‘n`th root of `self`



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

def inrt n
  (abs ** Rational(1, n)).round(5).floor
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

#inv_mod(m) ⇒ Object



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

def inv_mod m
  g, x, y = xgcd(m) 
  x % m if g == 1
end

#isqrtObject



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

def isqrt
  sqrt.floor
end

#jacobi(n) ⇒ Integer?

Returns the Jacobi symbol for ‘a`/`n`

For any integer ‘a` and any positive odd integer `n` the Jacobi symbol is defined as the product of the Legendre symbols corresponding to the prime factors of `n`.

Parameters:

  • p (Integer)

    The “denominator”

Returns:

  • (Integer, nil)

    -1, 0, 1, or ‘nil`



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

def jacobi n
  kronecker(n) if n.odd? and n > 0
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

#kronecker(b) ⇒ Integer

Returns the Kronecker symbol for ‘self`/`b`

The Kronecker symbol is an extension of the Jacobi symbol to all integers.

2.kronecker 3 #=> -1
-8.kronecker 3 #=> 1
6.kronecker 7 #=> -1

Parameters:

  • b (Integer)

    The “denominator”

Returns:



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

def kronecker b
  # The following algorithm is excerpted from Henri Cohen's A Course
  # in Computational Algebraic Number Theory, 3rd. ed. It appears on
  # page 48, and is entitled "Algorithm 1.4.12 (Kronecker-Binary).

  # Given a, b ∈ ℤ, this algorithm computes the Kronecker symbol
  # (a/b) (hence the Legendre symbol when b is an odd prime).
  raise ArgumentError unless b.is_a?(Integer)

  a = self
  # The following Array is a lookup table for computing (-1)^(a^2 -
  # 1)/8 (Cohen, p. 29)
  tab2 = [0, 1, 0, -1, 0, -1, 0, 1]

  # 1. [Test b = 0] If b = 0, then output 0 if |a| ≠ 1, 1 if |a| = 1
  # and terminate the algorithm
  return a.abs == 1 ? 1 : 0 if b.zero?

  # 2. [Remove 2's from b] If a and b are both even, output 0 and
  # terminate the algorithm. Otherwise, set v ← 0 and while b is
  # even set v ← v + 1 and b ← b/2. Then if v is even set k ← 1,
  # otherwise set k ← (-1)^(a^2 - 1)/8 (by table lookup, not by
  # computing (a^2 - 1)/8). Finally, if b < 0 set b ← -b, and if in
  # addition a < 0 set k ← -k.
  return 0 if a.even? and b.even?
  v, k = 0, nil
  while b.even?
    v += 1
    b = b.quo(2).to_i
  end
  k = v.even? ? 1 : tab2[a&7]
  if b < 0
    b = -b
    k =-k if a < 0
  end

  # 3. [Reduce size once] (Here b is odd and b > 0.) Set a ← a mod b
  raise unless b.odd? and b > 0
  a %= b

  loop do
    # 4. [Finished?] If a = 0, output 0 if b > 1, k if b = 1, and
    # terminate the algorithm
    return (b > 1) ? 0 : k if a.zero?

    # 5. [Remove powers of 2] Set v ← 0 and, while a is even, set v ←
    # v + 1 and a ← a/2. If v is odd, set k ← (-1)^((b^2 - 1)/8) * k
    v = 0
    while a.even?
      v += 1
      a = a.quo(2).to_i
    end
    k = ((-1)**((b**2).pred.quo 8) * k).to_i if v.odd?
    
    # 6. [Subtract and apply reciprocity] (Here a and b are odd.) Set
    # r ← b - a. If r > 0, then set k ← (-1)^((a-1)(b-1)/4) * k (using
    # if statements), b ← a and a ← r, else set a ← -r. Go to step 4.
    raise unless a.odd? and b.odd?
    r = b - a
    if r > 0
      # The optimisation below is from Cohen, p. 29
      k = -k unless (a & b & 2).zero?
      b = a
      a = r
    else
      a = -r
    end   
  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

#legendre(p) ⇒ Integer?

Returns the Legendre symbol for ‘self`/`p`

The Legendre symbol is a multiplicative function with values 1, −1, 0: its value on a (nonzero) quadratic residue mod ‘p` is 1 and on a quadratic non-residue is −1. It is defined only when `p` is an odd prime.

12345.legendre 331 #=> -1
0.legendre 83 #=> 0
55.legendre 10 #=> nil
6.legendre 7 #=> -1

Parameters:

  • p (Integer)

    The “denominator”

Returns:

  • (Integer, nil)

    -1, 0, 1, or ‘nil`



98
99
100
# File 'lib/numb/kronecker.rb', line 98

def legendre p
  kronecker(p) if p.odd? and p > 2 and p.prime?
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)


401
402
403
# File 'lib/numb/divisors.rb', line 401

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

#ord(m) ⇒ Integer?

Returns the multiplicative order of ‘self` % `m`, or `nil` if `self` is not coprime to `m`

Given an integer ‘self` and a positive integer `m` with gcd(`a`, `m`) = 1, the multiplicative order of `self` modulo `m` is the smallest positive integer `k` with: `self`^`k` ≡ 1 (modulo `m`).

Parameters:

Returns:

  • (Integer, nil)

    the power, ‘k`, or `nil` if `self` and `m` are not coprime



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

def ord(m)
  return unless coprime?(m)
  m.prime_division.inject(1) do |result, f|
    (p, k), r = f, 1
    pk = p ** k
    # We could calculate the totient here as `(p - 1) * p ** (k -
    # 1)`, but it feels cleaner to separate the logic
    (t = pk.φ).prime_division.each do |q, e|
      x = power_mod(t / q ** e, pk)
      while x != 1
        r *= q
        x = x.power_mod(q, pk)
      end
    end      
    result.lcm(r)
  end
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

#ordinary?Boolean

Returns:

  • (Boolean)


444
445
446
447
448
449
450
451
# File 'lib/numb/divisors.rb', line 444

def ordinary?
  return true if self == 1
  pf = prime_factors.sort.reverse
  Prime.first(pf.size).
        zip(pf).
        map{|b,e| b**(e-1)}.
        reduce(:*) == first_with_n_divisors
end

#ore?Boolean Also known as: harmonic_divisor?

Returns:

  • (Boolean)


260
261
262
263
# File 'lib/numb/divisors.rb', line 260

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



333
334
335
336
337
338
# File 'lib/numb/divisors.rb', line 333

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

#perfect_totient?true, false

Returns ‘true` if `self` is equal to the sum of its iterated totients, otherwise `false`

For example: φ(183) = 120

φ(120)  = 32
φ(32)   = 16
φ(16)    = 8
φ(4)     = 2
φ(2)     = 1

120 + 32 + 16 + 8 + 4 + 2 + 1 = 183

Returns:

  • (true, false)

    ‘true` if `self` is a perfect totient; `false` otherwise.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/numb/totient.rb', line 23

def perfect_totient?
  # TODO: Possible optimisation: once the totient is a power of 2,
  # which we identify using bit ops, it is predictable what totients
  # will follow. For example, consider 441027. Its iterated totients
  # are [294012, 97992, 32640, 8192, 4096, 2048, 1024, 512, 256,
  # 128, 64, 32, 16, 8, 4, 2, 1], i.e. 17 iterations are
  # needed. Once we hit 8192, we can derive [2, 4, 8, 16, 32, 64,
  # 128, 256, 512, 1024, 2048, 4096, 8192], add the 1, then return.

  # TODO: The more obvious tweak is to return true immediately when
  # self is a power of 3. I want to write a #power_of? predicate for
  # the general case first, then benchmark it for use here.
  return false if even?
  a = [totient]
  sum = a.first
  until a.last == 1 or sum > self
    a << a.last.totient
    sum += a.last
  end
  sum == 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)


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

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

#politenessObject



126
127
128
# File 'lib/numb/divisors.rb', line 126

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

#power_mod(b, m) ⇒ Integer

‘self`^`b` mod `m`

Parameters:

  • b (Integer)

    power to which ‘self` should be raised

  • m (Integer)

    modulus

Returns:



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

def power_mod(b, m)
  result = 1
  b.to_s(2).chars.each do |bit|
    result = (result * result) % m
    result = (result * self) % m if bit==?1
  end
  result
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)


270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/numb/divisors.rb', line 270

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)


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

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



139
140
141
# File 'lib/numb/divisors.rb', line 139

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



437
438
439
440
441
442
# File 'lib/numb/divisors.rb', line 437

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)


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

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)


305
306
307
# File 'lib/numb/divisors.rb', line 305

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

#rulerObject



409
410
411
# File 'lib/numb/divisors.rb', line 409

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



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# File 'lib/numb/divisors.rb', line 413

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)


296
297
298
299
# File 'lib/numb/divisors.rb', line 296

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

#smooth?(b) ⇒ Boolean

Returns:

  • (Boolean)


301
302
303
# File 'lib/numb/divisors.rb', line 301

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



405
406
407
# File 'lib/numb/divisors.rb', line 405

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)


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

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

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



151
152
153
# File 'lib/numb/divisors.rb', line 151

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



183
184
185
# File 'lib/numb/divisors.rb', line 183

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)


309
310
311
# File 'lib/numb/divisors.rb', line 309

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)


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

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)


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

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

#xgcd(b) ⇒ Array<Integer>

Computes the extended greatest common divisor of ‘self` and `b`

The extended Euclidean algorithm is an extension to the Euclidean algorithm for finding the GCD of integers ‘a` and `b`: it also finds the integers `x` and `y` in Bézout’s identity:

ax + by = gcd(a, b)

This method takes ‘self` as `a`, and `b` as an argument, and returns their GCD, `x`, and `y`

For example, ‘21.xgcd(48)` is `[3, 7, -3]` because `21.gcd(48)` is `3`, and `21 * 7 + 48 * -3` is `3`.

3.xgcd(-65) #=> [1, 22, 1]
56.xgcd(72) #=> [8, 4, -3]

Parameters:

  • b (Integer)

    the number ‘self` is divided by

Returns:

  • (Array<Integer>)

    GCD, ‘x`, and `y`



476
477
478
479
480
481
482
483
484
485
# File 'lib/numb/divisors.rb', line 476

def xgcd b
  a = self
  x, y, u, v = 0, 1, 1, 0
  while a != 0
    q, r = b/a, b%a 
    m, n = x-u*q, y-v*q
    b, a, x, y, u, v = a, r, u, v, m, n
  end    
  self < 0 ? [b, x, y].map(&:-@) : [b, x, y]
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



168
169
170
171
172
# File 'lib/numb/divisors.rb', line 168

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



176
177
178
# File 'lib/numb/divisors.rb', line 176

def σ∞
  infinitary_divisors.reduce :+
end

#τObject Also known as: number_of_divisors, d

Returns the number of divisors of self



317
318
319
320
321
322
323
324
325
326
327
# File 'lib/numb/divisors.rb', line 317

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