Strong and weak primes: Difference between revisions

m (→‎{{header|Sidef}}: Fix link: Perl 6 --> Raku)
Line 844:
There are 21,837 balanced primes less than 10 million.
</pre>
 
=={{header|Kotlin}}==
{{trans|Java}}
<lang scala>private const val MAX = 10000000 + 1000
private val primes = BooleanArray(MAX)
 
fun main() {
sieve()
 
println("First 36 strong primes:")
displayStrongPrimes(36)
for (n in intArrayOf(1000000, 10000000)) {
System.out.printf("Number of strong primes below %,d = %,d%n", n, strongPrimesBelow(n))
}
 
println("First 37 weak primes:")
displayWeakPrimes(37)
for (n in intArrayOf(1000000, 10000000)) {
System.out.printf("Number of weak primes below %,d = %,d%n", n, weakPrimesBelow(n))
}
}
 
private fun weakPrimesBelow(maxPrime: Int): Int {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (currentPrime < maxPrime) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 < priorPrime + nextPrime) {
count++
}
priorPrime = currentPrime
currentPrime = nextPrime
}
return count
}
 
private fun displayWeakPrimes(maxCount: Int) {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (count < maxCount) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 < priorPrime + nextPrime) {
count++
print("$currentPrime ")
}
priorPrime = currentPrime
currentPrime = nextPrime
}
println()
}
 
private fun getNextPrime(currentPrime: Int): Int {
var nextPrime = currentPrime + 2
while (!primes[nextPrime]) {
nextPrime += 2
}
return nextPrime
}
 
private fun strongPrimesBelow(maxPrime: Int): Int {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (currentPrime < maxPrime) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 > priorPrime + nextPrime) {
count++
}
priorPrime = currentPrime
currentPrime = nextPrime
}
return count
}
 
private fun displayStrongPrimes(maxCount: Int) {
var priorPrime = 2
var currentPrime = 3
var count = 0
while (count < maxCount) {
val nextPrime = getNextPrime(currentPrime)
if (currentPrime * 2 > priorPrime + nextPrime) {
count++
print("$currentPrime ")
}
priorPrime = currentPrime
currentPrime = nextPrime
}
println()
}
 
private fun sieve() { // primes
for (i in 2 until MAX) {
primes[i] = true
}
for (i in 2 until MAX) {
if (primes[i]) {
var j = 2 * i
while (j < MAX) {
primes[j] = false
j += i
}
}
}
}</lang>
{{out}}
<pre>First 36 strong primes:
11 17 29 37 41 59 67 71 79 97 101 107 127 137 149 163 179 191 197 223 227 239 251 269 277 281 307 311 331 347 367 379 397 419 431 439
Number of strong primes below 1,000,000 = 37,723
Number of strong primes below 10,000,000 = 320,991
First 37 weak primes:
3 7 13 19 23 31 43 47 61 73 83 89 103 109 113 131 139 151 167 181 193 199 229 233 241 271 283 293 313 317 337 349 353 359 383 389 401
Number of weak primes below 1,000,000 = 37,780
Number of weak primes below 10,000,000 = 321,750</pre>
 
=={{header|Lua}}==
1,452

edits