How to resolve the algorithm Vampire number step by step in the Nim programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Vampire number step by step in the Nim programming language
Table of Contents
Problem Statement
A vampire number is a natural decimal number with an even number of digits, that can be factored into two integers. These two factors are called the fangs, and must have the following properties:
An example of a vampire number and its fangs: 1260 : (21, 60)
16758243290880, 24959017348650, 14593825548650
Note that a vampire number can have more than one pair of fangs.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Vampire number step by step in the Nim programming language
Source code in the nim programming language
import algorithm, math, sequtils, strformat, strutils, sugar
const Pow10 = collect(newSeq, for n in 0..18: 10 ^ n)
template isOdd(n: int): bool = (n and 1) != 0
proc fangs(n: Positive): seq[(int, int)] =
## Return the list fo fangs of "n" (empty if "n" is not vampiric).
let nDigits = sorted($n)
if nDigits.len.isOdd: return @[]
let fangLen = nDigits.len div 2
let inf = Pow10[fangLen - 1]
let sup = inf * 10 - 1
for d in inf..sup:
if n mod d != 0: continue
let q = n div d
if q < d: return
let dDigits = $d
let qDigits = $q
if qDigits.len > fangLen: continue
if qDigits.len < fangLen: return
if nDigits != sorted(dDigits & qDigits): continue
if dDigits[^1] != '0' or qDigits[^1] != '0':
# Finally, "n" is vampiric. Add the fangs to the result.
result.add (d, q)
echo "First 25 vampire numbers with their fangs:"
var count = 0
var n = 10
var limit = 100
while count != 25:
let fangList = n.fangs
if fangList.len != 0:
inc count
echo &"{count:2}: {n:>6} = ", fangList.mapIt(&"{it[0]:3} × {it[1]:3}").join(" = ")
inc n
if n == limit:
n *= 10
limit *= 10
echo()
for n in [16_758_243_290_880, 24_959_017_348_650, 14_593_825_548_650]:
let fangList = n.fangs
if fangList.len == 0:
echo &"{n} is not vampiric."
else:
echo &"{n} = ", fangList.mapIt(&"{it[0]} × {it[1]}").join(" = ")
You may also check:How to resolve the algorithm Introspection step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Arithmetic numbers step by step in the Quackery programming language
You may also check:How to resolve the algorithm Yin and yang step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Sort an integer array step by step in the Ruby programming language
You may also check:How to resolve the algorithm Cartesian product of two or more lists step by step in the SQL programming language