Lösungen Sitzung 3¶
Aufgabe
Gebe alle geraden Zahlen zwischen 1 und inklusive 100 aus
Hinweis: Siehe modolu Funktion, in Python %
, welche den Rest einer ganzzahligen Division angibt, also die Zahl \(b\) bei
\(n = m*a +b, 0 <= b < |m|\)
Beispiele:
2 % 5 = 2 # 0 * 5 + 2
8 % 5 = 3 # 1 * 5 + 3
42 % 13 = 3 # 13 * 3 + 3
16 % 2 = 0 # 8*2 + 0
17 % 2 = 1 # 8*2 + 1
18 % 2 = 0 # 9*2 + 0
for i in range(1, 101): # range ist oben nicht inklusive, deshalb 101
# eine zahl i ist gerade genau dann wenn i modolu 2 = 0 ist
if i%2 == 0:
print(i)
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
Aufgabe
Schreibe eine Funktion die einen Boolean Wert zurückliefert ob eine Zahl gerade ist oder nicht.
def is_even(number):
return number % 2 == 0
print(is_even(2))
True
Bonus Aufgabe
Berechne alle Primzahlen zwischen 0 und 100
Hinweis 1: Der Modolu Operator %
berechnet den Rest der bei einer Operationen zwischen zwei ganzen Zahlen entsteht.
2 % 5 = 2 # 0 * 5 + 2
8 % 5 = 3 # 1 * 5 + 3
42 % 13 = 3 # 13 * 3 + 3
Hinweis 2: Eine Primzahl ist eine natürliche Zahl, die größer als 1 und ausschließlich durch sich selbst und durch 1 teilbar ist.
Hinweis 3:
range(0, 100) = [0, 1, 2, ..., 99]
for i in range(2, 101):
is_prime = True
for j in range(2, i):
if i%j == 0:
is_prime = False
if is_prime:
print(f'{i} is prime')
else:
print(f'{i} is NOT prime')
2 is prime
3 is prime
4 is NOT prime
5 is prime
6 is NOT prime
7 is prime
8 is NOT prime
9 is NOT prime
10 is NOT prime
11 is prime
12 is NOT prime
13 is prime
14 is NOT prime
15 is NOT prime
16 is NOT prime
17 is prime
18 is NOT prime
19 is prime
20 is NOT prime
21 is NOT prime
22 is NOT prime
23 is prime
24 is NOT prime
25 is NOT prime
26 is NOT prime
27 is NOT prime
28 is NOT prime
29 is prime
30 is NOT prime
31 is prime
32 is NOT prime
33 is NOT prime
34 is NOT prime
35 is NOT prime
36 is NOT prime
37 is prime
38 is NOT prime
39 is NOT prime
40 is NOT prime
41 is prime
42 is NOT prime
43 is prime
44 is NOT prime
45 is NOT prime
46 is NOT prime
47 is prime
48 is NOT prime
49 is NOT prime
50 is NOT prime
51 is NOT prime
52 is NOT prime
53 is prime
54 is NOT prime
55 is NOT prime
56 is NOT prime
57 is NOT prime
58 is NOT prime
59 is prime
60 is NOT prime
61 is prime
62 is NOT prime
63 is NOT prime
64 is NOT prime
65 is NOT prime
66 is NOT prime
67 is prime
68 is NOT prime
69 is NOT prime
70 is NOT prime
71 is prime
72 is NOT prime
73 is prime
74 is NOT prime
75 is NOT prime
76 is NOT prime
77 is NOT prime
78 is NOT prime
79 is prime
80 is NOT prime
81 is NOT prime
82 is NOT prime
83 is prime
84 is NOT prime
85 is NOT prime
86 is NOT prime
87 is NOT prime
88 is NOT prime
89 is prime
90 is NOT prime
91 is NOT prime
92 is NOT prime
93 is NOT prime
94 is NOT prime
95 is NOT prime
96 is NOT prime
97 is prime
98 is NOT prime
99 is NOT prime
100 is NOT prime