Skip to content

Commit 5408cfa

Browse files
committed
tp2 solution
1 parent 073e9e8 commit 5408cfa

File tree

1 file changed

+31
-1
lines changed
  • tp2/src/main/kotlin/fmt/kotlin/fundamentals

1 file changed

+31
-1
lines changed

tp2/src/main/kotlin/fmt/kotlin/fundamentals/Tp2.kt

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,36 @@ package fmt.kotlin.fundamentals
33
class Tp2 {
44

55
fun getFirstPrimeNumbers(nbToFind: Int): List<Int> {
6-
return arrayListOf<Int>()
6+
// The list containing all the prime numbers we found
7+
// It is a val because we will modify the array but not build a new array each time we add something to it
8+
val primeNumbers = arrayListOf<Int>()
9+
10+
// Start with 2 as 0 and 1 are not prime numbers
11+
// n is a var because we will change it at the end of each loop to test the next number
12+
var n = 2;
13+
14+
// Iterate while we don't have enough prime numbers in the list we want to return
15+
while (primeNumbers.size < nbToFind) {
16+
var prime = true
17+
18+
// Iterate over every number until the one we want to test to see if it can be divided
19+
for (i in 2..n - 1) {
20+
if (n % i == 0) {
21+
prime = false
22+
// It if can be divided once, no need to test other numbers
23+
break
24+
}
25+
}
26+
27+
// Add it to the list we want to return, if we did not find a divisor
28+
if (prime) {
29+
primeNumbers.add(n);
30+
}
31+
32+
// We try the next number
33+
n++
34+
}
35+
36+
return primeNumbers
737
}
838
}

0 commit comments

Comments
 (0)