Skip to content

Commit

Permalink
tp2 solution
Browse files Browse the repository at this point in the history
  • Loading branch information
ctruchi committed Feb 7, 2025
1 parent 073e9e8 commit 5408cfa
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion tp2/src/main/kotlin/fmt/kotlin/fundamentals/Tp2.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,36 @@ package fmt.kotlin.fundamentals
class Tp2 {

fun getFirstPrimeNumbers(nbToFind: Int): List<Int> {
return arrayListOf<Int>()
// The list containing all the prime numbers we found
// It is a val because we will modify the array but not build a new array each time we add something to it
val primeNumbers = arrayListOf<Int>()

// Start with 2 as 0 and 1 are not prime numbers
// n is a var because we will change it at the end of each loop to test the next number
var n = 2;

// Iterate while we don't have enough prime numbers in the list we want to return
while (primeNumbers.size < nbToFind) {
var prime = true

// Iterate over every number until the one we want to test to see if it can be divided
for (i in 2..n - 1) {
if (n % i == 0) {
prime = false
// It if can be divided once, no need to test other numbers
break
}
}

// Add it to the list we want to return, if we did not find a divisor
if (prime) {
primeNumbers.add(n);
}

// We try the next number
n++
}

return primeNumbers
}
}

0 comments on commit 5408cfa

Please sign in to comment.