Iterated digits squaring: Difference between revisions
Content added Content deleted
(Scala contribution added.) |
(Add Swift) |
||
Line 2,659: | Line 2,659: | ||
}</lang> |
}</lang> |
||
=={{header|Swift}}== |
|||
{{trans|C}} |
|||
{{libheader|Attaswift BigInt}} |
|||
With nth power support. |
|||
<lang swift>import BigInt |
|||
func is89(_ n: Int) -> Bool { |
|||
var n = n |
|||
while true { |
|||
var s = 0 |
|||
repeat { |
|||
s += (n%10) * (n%10) |
|||
n /= 10 |
|||
} while n > 0 |
|||
if s == 89 { |
|||
return true |
|||
} else if s == 1 { |
|||
return false |
|||
} |
|||
n = s |
|||
} |
|||
} |
|||
func iterSquare(upToPower pow: Int) { |
|||
var sums = [BigInt](repeating: 0, count: pow * 81 + 1) |
|||
sums[0] = 1 |
|||
for n in 1...pow { |
|||
var i = n * 81 |
|||
while i > 0 { |
|||
for j in 1..<10 { |
|||
let s = j * j |
|||
guard s <= i else { break } |
|||
sums[i] += sums[i-s] |
|||
} |
|||
i -= 1 |
|||
} |
|||
var count89 = BigInt(0) |
|||
for x in 1..<n*81 + 1 { |
|||
guard is89(x) else { continue } |
|||
count89 += sums[x] |
|||
} |
|||
print("1->10^\(n): \(count89)") |
|||
} |
|||
} |
|||
iterSquare(upToPower: 8)</lang> |
|||
{{out}} |
|||
<pre>1->10^1: 7 |
|||
1->10^2: 80 |
|||
1->10^3: 857 |
|||
1->10^4: 8558 |
|||
1->10^5: 85623 |
|||
1->10^6: 856929 |
|||
1->10^7: 8581146 |
|||
1->10^8: 85744333</pre> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
All three versions below produce identical output (<tt>85744333</tt>), but the third is fastest and the first is the slowest, both by substantial margins. |
All three versions below produce identical output (<tt>85744333</tt>), but the third is fastest and the first is the slowest, both by substantial margins. |