You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
if num %2==0 { returnfalse } // Eliminate even numbers
8
+
9
+
for i in3...Int(Double(num).squareRoot()) where i %2!=0 {
10
+
if num % i ==0 {
11
+
returnfalse
12
+
}
13
+
}
14
+
returntrue
15
+
}
16
+
```
17
+
18
+
## C++ implementation
19
+
20
+
```C++
21
+
#include<iostream>
22
+
#include<cmath>
23
+
24
+
boolisPrime(int num) {
25
+
if (num < 2) return false;
26
+
if (num == 2) return true;
27
+
if (num % 2 == 0) return false; // Eliminate even numbers
28
+
29
+
for (int i = 3; i <= sqrt(num); i += 2) { // Check only odd numbers
30
+
if (num % i == 0) {
31
+
return false;
32
+
}
33
+
}
34
+
return true;
35
+
}
36
+
```
37
+
38
+
## Explanation
39
+
Some of the observations I've made are that both code implementations had an `isPrime` function.
40
+
41
+
For both, if the number is less than 2 it returns false (`if num < 2 { return false }`). If the number is even to 2 it returns true (`if num == 2 { return true }`). If the number is divided by 2 and equals 0 it returns false ( `if num % 2 == 0 { return false }`).
42
+
43
+
I noticed both languages have `bool` in code but in different spaces.
44
+
45
+
Swift and C++ have the same loop variable (i)
46
+
47
+
Both codes include If (`num % i == 0`). Taking the number divided by `i = 0`.
48
+
49
+
### Differences
50
+
51
+
In C++ the code starts off with `#include <iostream> #include <cmath>`.
52
+
53
+
Before the function `isPrime` Swift starts with `func` but C++ starts with `bool`.
54
+
55
+
Even though both codes have square root it is formatted differently (`.squareRoot()` and `sqrt()`) in the code.
56
+
57
+
Swift has `Double(num)` in the code where C++ does not include this.
58
+
59
+
In Swift the code does not declare the `i` but C++ declares the `i`.
0 commit comments