aboutsummaryrefslogtreecommitdiff
path: root/challenge-133/iangoodnight/javascript/ch-2.js
blob: 5f229008ecfbc412d45f0d767046fe3eabccac80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env node
// ch-2.js

/**
 * https://theweeklychallenge.org/blog/perl-weekly-challenge-133/
 *
 * Task 2 > Smith Numbers
 * ======================
 *
 * Write a script to generate the first 10 `Smith Numbers` in base 10.
 *
 * According to Wikipedia:
 *
 * > In number theory, a Smith number is a composite number for which, in a
 * > given number base, the sum of its digits is equal to the sum of the digits
 * > in its prime factorization in the given number base.
 *
 **/

'use strict';

/**
 * Our PWC solution and some helper functions
 **/

// First, we need a utility function to return our prime factors
function primeFactors(number) {
  let n = parseInt(number, 10); // Input validation
  if (number === 'NaN') {
    // Fail fast if arg is not a positive integer
    throw new Error(
      'function `primeFactors` expects a positive integer as an argument.',
    );
  }
  const factors = [];

  let divisor = 2; // Starting with 2, check for remainder
  while (n >= 2) {
    if (n % divisor === 0) {
      // If modulo is 0, push to factors
      factors.push(divisor);
      n /= divisor;
    } else {
      divisor += 1; // Else, increment the divisor and try again
    }
  }
  return factors;
}

// Reduce numbers to the sum of their digits
function sumDigits(number) {
  return number
    .toString()
    .split('')
    .reduce((sum, digit) => sum + parseInt(digit, 10), 0);
}

// Find our actual smith numbers with the help of `primeFactors` and `sumDigits`
function identifySmithNumbers(limit = 10) {
  const smithNumbers = [];

  let test = 4; // Smith numbers are composite numbers, so skip the primes
  while (smithNumbers.length < limit) {
    const primeFactorsArr = primeFactors(test);

    const factorSum = primeFactorsArr.reduce(
      (sum, factor) => sum + sumDigits(factor),
      0,
    );

    const digitSum = sumDigits(test);

    if (factorSum === digitSum && primeFactorsArr.length !== 1) {
      smithNumbers.push(test);
    }
    test += 1;
  }
  return smithNumbers;
}

/**
 * General utilities
 **/

// Takes an array and returns it as human-readable comma separated list
function stringWithOxfordComma(arr = []) {
  const reversed = [...arr].reverse();

  const [last, ...rest] = reversed;

  const first = [...rest].reverse().join(', ');

  return `${first}, and ${last}`;
}

// IIFE to handle args and print results
(function main() {
  const limit = process.argv[2] || 10;

  const smithNumbers = identifySmithNumbers(limit);

  const stringified = stringWithOxfordComma(smithNumbers);

  console.log(`The first ${limit} Smith Numbers are ${stringified}.`);
})();