Brilliant numbers: Difference between revisions

Swift
(Swift)
Line 1,001:
First brilliant number >= 10^12 is 1000006000009 at position 2409600866
</pre>
 
=={{header|Swift}}==
 
<lang rebol>func primeArray(n: Int) -> [Bool] {
var primeArr = [Bool](repeating: true, count: n + 1)
primeArr[0] = false // setting zero to be not prime
primeArr[1] = false // setting one to be not prime
// finding all primes which are divisible by p and are greater than or equal to the square of it
var p = 2
while (p * p) <= n {
if primeArr[p] == true {
for j in stride(from: p * 2, through: n, by: p) {
primeArr[j] = false
}
}
p += 1
}
return primeArr
}
 
 
func digitsCount(n: Int) -> Int {
// count number of digits for a number
// increase the count if n divide by 10 is not equal to zero
var num = n
var count = 0;
while num != 0 {
num = num/10
count += 1
}
return count
}
 
 
func isBrilliant(n: Int) -> Bool {
// Set the prime array
var isPrime = [Bool]()
isPrime = primeArray(n: n)
// Check if the number is the product of two prime numbers
// Also check if the digit counts of those prime numbers are the same.
for i in stride(from: 2, through: n, by: 1) { // i=2, n=50
let x = n / i // i=2, n=50, x=25
if (isPrime[i] && isPrime[x] && x * i == n) { // i=2, x=50, false
if (digitsCount(n: i) == digitsCount(n: x)) {
return true
}
}
}
return false
}
 
 
func print100Brilliants() {
// Print the first 100 brilliant numbers
var brilNums = [Int]()
var count = 4
while brilNums.count != 100 {
if isBrilliant(n: count) {
brilNums.append(count)
}
count += 1
}
print("First 100 brilliant numbers:\n", brilNums)
}
 
 
func printBrilliantsOfMagnitude() {
// Print the brilliant numbers of base 10 up to magnitude of 6
// Including their positions in the array.
var basePower = 10.0
var brilNums: [Double] = [0.0]
var count = 1.0
while basePower != pow(basePower, 6) {
if isBrilliant(n: Int(count)) {
brilNums.append(count)
if count >= basePower {
print("First brilliant number >= \(Int(basePower)): \(Int(count)) at position \(brilNums.firstIndex(of: count)!)")
basePower *= 10
}
}
count += 1
}
}
 
 
print100Brilliants()
printBrilliantsOfMagnitude()</lang>
 
{{out}}
 
<pre>First 100 brilliant numbers:
4 6 9 10 14 15 21 25 35 49
121 143 169 187 209 221 247 253 289 299
319 323 341 361 377 391 403 407 437 451
473 481 493 517 527 529 533 551 559 583
589 611 629 649 667 671 689 697 703 713
731 737 767 779 781 793 799 803 817 841
851 869 871 893 899 901 913 923 943 949
961 979 989 1003 1007 1027 1037 1067 1073 1079
1081 1121 1139 1147 1157 1159 1189 1207 1219 1241
1247 1261 1271 1273 1333 1343 1349 1357 1363 1369
 
First brilliant number >= 10: 10 at position 4
First brilliant number >= 100: 121 at position 11
First brilliant number >= 1000: 1003 at position 74
First brilliant number >= 10000: 10201 at position 242
First brilliant number >= 100000: 100013 at position 2505
First brilliant number >= 1000000: 1018081 at position 10538</pre>
 
=={{header|Wren}}==