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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Smith numbers step by step in the Tcl 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 Tcl programming language

Source code in the tcl programming language

proc factors {x} {
    # list the prime factors of x in ascending order
    set result [list]
    while {$x % 2 == 0} {
        lappend result 2
        set x [expr {$x / 2}]
    }
    for {set i 3} {$i*$i <= $x} {incr i 2} {
        while {$x % $i == 0} {
            lappend result $i
            set x [expr {$x / $i}]
        }
    }
    if {$x != 1} {lappend result $x}
    return $result
}

proc digitsum {n} {
    ::tcl::mathop::+ {*}[split $n ""]
}

proc smith? {n} {
    set fs [factors $n]
    if {[llength $fs] == 1} {
        return false    ;# $n is prime
    }
    expr {[digitsum $n] == [digitsum [join $fs ""]]}
}
proc range {n} {
    for {set i 1} {$i < $n} {incr i} {lappend result $i}
    return $result
}

set smiths [lmap i [range 10000] {
    if {![smith? $i]} continue
    set i
}]

puts [lrange $smiths 0 12]...
puts ...[lrange $smiths end-12 end]
puts "([llength $smiths] total)"


  

You may also check:How to resolve the algorithm Reflection/List properties step by step in the J programming language
You may also check:How to resolve the algorithm Hello world/Newline omission step by step in the Pict programming language
You may also check:How to resolve the algorithm Sockets step by step in the Wren programming language
You may also check:How to resolve the algorithm Dining philosophers step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Knuth shuffle step by step in the CMake programming language