File tree Expand file tree Collapse file tree 1 file changed +31
-1
lines changed
tp2/src/main/kotlin/fmt/kotlin/fundamentals Expand file tree Collapse file tree 1 file changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -3,6 +3,36 @@ package fmt.kotlin.fundamentals
3
3
class Tp2 {
4
4
5
5
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
7
37
}
8
38
}
You can’t perform that action at this time.
0 commit comments