Skip to content

Commit 03d0a0e

Browse files
authored
feat: adds Bryana's code samples (#162)
1 parent a879367 commit 03d0a0e

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
## Swift implementation
2+
3+
```Swift
4+
func isPrime(_ num: Int) -> Bool {
5+
if num < 2 { return false }
6+
if num == 2 { return true }
7+
if num % 2 == 0 { return false } // Eliminate even numbers
8+
9+
for i in 3...Int(Double(num).squareRoot()) where i % 2 != 0 {
10+
if num % i == 0 {
11+
return false
12+
}
13+
}
14+
return true
15+
}
16+
```
17+
18+
## C++ implementation
19+
20+
```C++
21+
#include <iostream>
22+
#include <cmath>
23+
24+
bool isPrime(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`.
60+
61+
62+
63+
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+

0 commit comments

Comments
 (0)