Skip to content

Instantly share code, notes, and snippets.

@KarmaBlackshaw
Last active December 21, 2021 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KarmaBlackshaw/a1d129dabcef93bb3b78b64203081185 to your computer and use it in GitHub Desktop.
Save KarmaBlackshaw/a1d129dabcef93bb3b78b64203081185 to your computer and use it in GitHub Desktop.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

const isPrime = num => {
  const sqrt = Math.sqrt(num)
  for (let i = 2; i <= sqrt; i++) {
    if (num % i === 0) {
      return false
    }
  }

  return num > 1
}

const getNthPrime = num => {
  const primes = []

  let i = 2
  while (primes.length < num) {
    if (isPrime(i)) {
      primes.push(i)
    }
    i++
  }
  return primes[num - 1]
}

console.log(getNthPrime(10001))
function middlePermutation (str) {
const letters = str.split('')
let results = [[letters.shift()]]
while (letters.length) {
const currLetter = letters.shift()
const tmpResults = []
results.forEach(result => {
let rIdx = 0
while (rIdx <= result.length) {
const tmp = [...result]
tmp.splice(rIdx, 0, currLetter)
tmpResults.push(tmp)
rIdx++
}
})
results = tmpResults
}
const middleIndex = Math.ceil(results.length / 2) - 1
return results.map(letterArray => letterArray.join(''))
.filter((el, idx, self) => (self.indexOf(el) === idx))
.sort()[middleIndex]
}
console.time('start')
console.log(middlePermutation('abc'))
console.log(middlePermutation('abcd'))
console.log(middlePermutation('abcdx'))
console.log(middlePermutation('abcdxg'))
console.log(middlePermutation('abcdxgz'))
console.log(middlePermutation('mzayvdsfuobqtheknlgwjcrx'))
console.timeLog('start')
/**
* If we were to set up a Tic-Tac-Toe game, we would want to know whether the board's
* current state is solved, wouldn't we? Our goal is to create a function that will check that for us!
*
* Assume that the board comes in the form of a 3x3 array, where the value
* is 0 if a spot is empty, 1 if it is an "X", or 2 if it is an "O", like so:
*
* [[0, 0, 1],
* [0, 1, 2],
* [2, 1, 0]]
*
* We want our function to return:
*
* -1 if the board is not yet finished (there are empty spots),
* 1 if "X" won,
* 2 if "O" won,
* 0 if it's a cat's game (i.e. a draw).
*
* You may assume that the board passed in is valid in the context of a game of Tic-Tac-Toe.
*/
const board = [
[0, 0, 1],
[0, 1, 2],
[2, 1, 0]
]
// SOLUTION 1
const isSolved = (arr) => {
// ? ROW WIN
const rowWin = arr.filter(array => array.every(item => item === array[0] && item !== 0))
if (rowWin.length) {
return rowWin[0][0]
}
const columnWin = arr
.map((val, key) => arr.map(x => x[key]))
.filter(array => array.every(item => item === array[0] && item !== 0))
if (columnWin.length) {
return columnWin[0][0]
}
const crossArray = arr.map((val, key) => val[key])
const crossArrayInverse = arr.reverse().map((val, key) => val[key])
const crossWin = [crossArray, crossArrayInverse]
.filter(array => array.every(item => item === array[0] && item !== 0))
if (crossWin.length) {
return crossWin[0][0]
}
const isDraw = !arr
.reduce((acc, curr) => [...acc, ...curr], [])
.some(x => x === 0)
return isDraw ? 0 : -1
}
// Solution 2
const isSolved = (arr) => {
const columnWin = arr.map((val, key) => arr.map(x => x[key]))
const crossArray = arr.map((val, key) => val[key])
const crossArrayInverse = arr.reverse().map((val, key) => val[key])
const isDraw = !arr.reduce((acc, curr) => [...acc, ...curr], []).some(x => x === 0)
const wins = [...arr, ...columnWin, crossArray, crossArrayInverse]
.filter(array => array.every(item => item === array[0] && item !== 0))
return wins.length
? wins[0][0]
: isDraw ? 0 : -1
}
console.log(isSolved(board))

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

const getEvenFiboSum = num => {
  let prev = 0
  let curr = 1
  let total = 0

  while (curr < num) {
    const sum = prev + curr

    if (sum < num && sum % 2 === 0) {
      total += sum
    }

    prev = curr
    curr = sum
  }

  return total
}

const evenFiboSum = getEvenFiboSum(4000)
console.log(evenFiboSum)

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

const isPrime = num => {
  const sqrt = Math.sqrt(num)
  for (let i = 2; i <= sqrt; i++) {
    if (num % i === 0) {
      return false
    }
  }

  return num > 1
}

const greatestPrime = num => {
  for (let i = num; i > 0; i--) {
    if (isPrime(i)) {
      return i
    }
  }
}

console.log(greatestPrime(1000000))

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

const main = num => {
  let sum = 0
  for (let i = 0; i < num; i++) {
    if (i % 3 === 0 || i % 5 === 0) {
      sum += i
    }
  }

  return sum
}

console.log(main(10))

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

const isPalindrome = num => {
  const arr = [...String(num)]

  if (arr.length % 2 === 0) {
    const half1 = arr.splice(0, arr.length / 2).join('')
    const half2 = arr.reverse().join('')

    return half1 === half2
  }
}

const getMaxPalindrom = num => {
  for (let i = num; i > 0; i--) {
    for (let j = num; j > 0; j--) {
      const prd = i * j
      if (isPalindrome(prd)) {
        return { prd, i, j }
      }
    }
  }
}

const palindrome = getMaxPalindrom(99)
// const palindrome = getMaxPalindrom(999)
// const palindrome = getMaxPalindrom(9999)
console.log(palindrome)

From roman numeral to number and vice versa

const dictionary = [
  [1000, 'M'],
  [500, 'D'],
  [100, 'C'],
  [50, 'L'],
  [10, 'X'],
  [5, 'V'],
  [4, 'IV'],
  [1, 'I']
]

const dictionaryByAmount = dictionary.reduce((acc, [amount, figure]) => {
  return { ...acc, [amount]: figure }
}, {})

const dictionaryByFigure = dictionary.reduce((acc, [amount, figure]) => {
  return { ...acc, [figure]: amount }
}, {})

const maxChars = Math.max(...dictionary.map(x => x[1].length))

const toRoman = num => {
  let number = num
  const amounts = dictionary
    .map(x => x[0])
    .sort((x, y) => Number(x) > Number(y) ? -1 : 1)

  const str = amounts.reduce((acc, curr) => {
    const hits = Math.floor(number / curr)
    const deduction = hits * curr
    const figure = dictionaryByAmount[curr]

    number -= deduction
    acc += figure.repeat(hits)
    return acc
  }, '')

  return str
}

const fromRoman = str => {
  let string = str
  let amount = 0

  while (string.length) {
    const data = (() => {
      for (let i = maxChars; i >= 1; i--) {
        const currFigure = string.substring(0, i)

        if (dictionaryByFigure[currFigure]) {
          return {
            figure: currFigure,
            amount: dictionaryByFigure[currFigure],
            chars: i
          }
        }
      }
    })()

    string = string.replace(data.figure, '')
    amount += data.amount
  }

  return amount
}

const roman = toRoman(500121)
const number = fromRoman(roman)

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

const isMultipleOf = (x, y, num) => {
  for (let i = x; i <= y; i++) {
    if (num % i !== 0) {
      return false
    }
  }
  return true
}

let hasFoundSmallestMultipe = false
let i = 1
while (!hasFoundSmallestMultipe) {
  if (isMultipleOf(1, 10, i)) {
    hasFoundSmallestMultipe = true
    continue
  }

  i++
}
console.log(i)

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a² + b² = c² For example, 3² + 4² = 9 + 16 = 25 = 5².

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

const sqr = x => x * x
const isTriplet = (x, y, z, sum) => {
  if (x < y && y < z) {
    if (sqr(x) + sqr(y) === sqr(z)) {
      if ((x + y + z) === sum) {
        return true
      }
    }
  }
}
const getTriplet = (num) => {
  for (let i = 1; i <= num; i++) {
    for (let j = 1; j <= num; j++) {
      for (let k = 1; k <= num; k++) {
        if (isTriplet(i, j, k, num)) {
          return { i, j, k }
        }
      }
    }
  }
}

console.log(getTriplet(1000))

The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385

The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

const getSumSquareDifference = num => {
  let sumOfSquares = 0
  let squareOfSum = 0

  for (let i = 1; i <= num; i++) {
    sumOfSquares += i * i
    squareOfSum += i
  }

  squareOfSum = squareOfSum * squareOfSum

  return squareOfSum - sumOfSquares
}

console.log(getSumSquareDifference(10))

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

const isPrime = num => {
  const sqrt = Math.sqrt(num)
  for (let i = 2; i <= sqrt; i++) {
    if (num % i === 0) {
      return false
    }
  }

  return num > 1
}

const getGetSummationOfPrimes = num => {
  let sum = 0
  for (let i = 2; i <= num; i++) {
    if (isPrime(i)) {
      sum += i
    }
  }
  return sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment