A Smith number is a composite number whose sum of digits in its prime factorization is equal to the sum of digits in the number itself. For example, 85 is a Smith number because:
85 = 5 x 17 (prime factorization) sum of digits in 85 = 8 + 5 = 13 sum of digits in 5 + 1 + 7 = 13
Here is a program in Swift that finds all the Smith numbers within a given range:
import Foundation
// Function to find the sum of digits in a number
func digitSum(_ number: Int) -> Int {
var sum = 0
var n = number
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
// Function to find prime factors of a number
func primeFactors(_ number: Int) -> [Int] {
var n = number
var factors = [Int]()
var divisor = 2
while n > 1 {
while (n % divisor) == 0 {
factors.append(divisor)
n /= divisor
}
divisor += 1
}
return factors
}
// Function to check if a number is a Smith number
func isSmithNumber(_ number: Int) -> Bool {
if number < 4 {
return false // Smith numbers are composite (greater than 1)
}
let digitSumOfNumber = digitSum(number)
let primeFactorsOfNumber = primeFactors(number)
let digitSumOfPrimeFactors = primeFactorsOfNumber.reduce(0) { $0 + digitSum($1) }
return digitSumOfNumber == digitSumOfPrimeFactors
}
// Find and print Smith numbers within a range
func findSmithNumbers(inRange range: ClosedRange<Int>) {
for num in range {
if isSmithNumber(num) {
print("Smith number found: \(num)")
}
}
}
// Example: Find Smith numbers between 1 and 1000
let range = 1...100
findSmithNumbers(inRange: range)This program defines functions to calculate the digit sum and prime factors of a number. Then, it checks each number within a specified range to see if it's a Smith number and prints any Smith numbers found within that range. You can adjust the range to search for Smith numbers within a different range of numbers.
When we run the program, it will output all the smith numbers up to the limit we set:
Smith number found: 4
Smith number found: 5
Smith number found: 7
Smith number found: 11
Smith number found: 13
Smith number found: 17
Smith number found: 19
Smith number found: 22
Smith number found: 23
Smith number found: 27
Smith number found: 29
Smith number found: 31
Smith number found: 37
Smith number found: 41
Smith number found: 43
Smith number found: 47
Smith number found: 53
Smith number found: 58
Smith number found: 59
Smith number found: 61
Smith number found: 67
Smith number found: 71
Smith number found: 73
Smith number found: 79
Smith number found: 83
Smith number found: 85
Smith number found: 89
Smith number found: 94
Smith number found: 97If you like the blog post, you can subscribe & buy me a coffee. ☕️ 💰
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.