1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
package functions
import java.io.File
import java.io.PrintWriter
class NombrePremier{
fun primeNumber() {
val maxPrime: Long = 10_000_000
var isPrime = mutableListOf<Boolean>()
// var isPrime = mutableListOf<Boolean>(false, false)
var primes = mutableListOf<Int>()
fun boucleTrue() {
try {
for (index in 0..maxPrime) {
isPrime.add(true)
}
isPrime[0] = false
isPrime[1] = false
println("✅ Successfully... Fun boucleTrue")
println("✅ Size of isPrime: ${isPrime.size}")
}
catch(ex: Exception) {
println("🛑 Exception message from fun boucleTrue(): 🛑 $ex.message")
}
}
boucleTrue()
fun boucleFalse() {
try {
for (i in 2..maxPrime) {
if (isPrime[i.toInt()]) { /* the same: replace this (isPrime[i] == true) */
var j = i * i
while (j <= maxPrime) {
isPrime[j.toInt()] = false
j += i
}
primes.add(i.toInt())
}
}
fun infos() {
println("✅ Successfully... Fun boucleFalse")
println("✅ All Primes Numbers: $primes")
println("✅ Numbers of primes number: ${primes.size}")
println("✅ Last Prime Number: ${primes.last()}")
}
infos()
}
catch(ex: Exception) {
println("🛑 Exception message from fun boucleFalse(): 🛑 $ex.message")
}
}
boucleFalse()
fun writeToFile() {
try {
// using java class java.io.PrintWriter
val writer = PrintWriter("files/JCfile.txt")
writer.append(primes.toString())
writer.println()
writer.close()
// using java class java.io.File
val fileName = "files/data.txt"
var file = File(fileName)
// create a new file
val isNewFileCreated: Boolean = file.createNewFile()
if (isNewFileCreated) {
println("✅ $fileName is created successfully.")
} else {
println("✅ $fileName already exists.")
}
file.appendText(primes.toString())
}
catch (ex: Exception) {
println("🛑 Exception message from fun writeToFile(): 🛑 $ex.message")
}
}
writeToFile()
fun isPrimeNumber() {
val num = 46337
var flag = false
for (i in 2..num / 2) {
// condition for nonprime number
if (num % i == 0) {
flag = true
break
}
}
if (!flag)
println("👉 $num 👉 is a prime number.")
else
println("👉 $num 👉 is not a prime number.")
}
isPrimeNumber()
}
} |
Partager