How to resolve the algorithm Smith numbers step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Smith numbers step by step in the Swift programming language

Table of Contents

Problem Statement

Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers.

Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number.

Write a program to find all Smith numbers below 10000.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Smith numbers step by step in the Swift programming language

Source code in the swift programming language

extension BinaryInteger {
  @inlinable
  public var isSmith: Bool {
    guard self > 3 else {
      return false
    }

    let primeFactors = primeDecomposition()

    guard primeFactors.count != 1 else {
      return false
    }

    return primeFactors.map({ $0.sumDigits() }).reduce(0, +) == sumDigits()
  }

  @inlinable
  public func primeDecomposition() -> [Self] {
    guard self > 1 else { return [] }

    func step(_ x: Self) -> Self {
      return 1 + (x << 2) - ((x >> 1) << 1)
    }

    let maxQ = Self(Double(self).squareRoot())
    var d: Self = 1
    var q: Self = self & 1 == 0 ? 2 : 3

    while q <= maxQ && self % q != 0 {
      q = step(d)
      d += 1
    }

    return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self]
  }

  @inlinable
  public func sumDigits() -> Self {
    return String(self).lazy.map({ Self(Int(String($0))!) }).reduce(0, +)
  }
}

let smiths = (0..<10_000).filter({ $0.isSmith })

print("Num Smith numbers below 10,000: \(smiths.count)")
print("First 10 smith numbers: \(Array(smiths.prefix(10)))")
print("Last 10 smith numbers below 10,000: \(Array(smiths.suffix(10)))")


  

You may also check:How to resolve the algorithm Arbitrary-precision integers (included) step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Polymorphic copy step by step in the Racket programming language
You may also check:How to resolve the algorithm Count in factors step by step in the DCL programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the PostScript programming language
You may also check:How to resolve the algorithm Straddling checkerboard step by step in the C++ programming language