Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
module Arithmetik where
2
3
-- Aufgabe 1.1
4
-- Berechnung der Potenz durch e-faches multiplizieren von b
5
-- Benötigt e Rekursionsschritte
6
pow1 :: Double -> Int -> Double
7
pow1 b 0 = 1
8
pow1 b e = b * (pow1 b (e-1))
9
10
-- Aufgabe 1.2
11
-- Berechnung der Potenz pow2(b,e) = b^e
12
-- Benötigt O(log_2(e)) Rekursionsschritte
13
pow2 :: Double -> Int -> Double
14
pow2 b 0 = 1
15
pow2 b e = if odd e
16
then b * pow2 b (e-1)
17
else pow2 (b*b) (quot e 2)
18
19
-- Aufgabe 1.3
20
-- Berechnung der Potenz pow3(b,e) = b^e mit einer Hilfsfunktion
21
pow3 :: Double -> Integer -> Double
22
pow3 b e
23
| e < 0 = error "Der Exponent muss nicht-negativ sein"
24
| otherwise = pow3h b e 1 where
25
pow3h b e acc
26
| e == 0 = acc
27
| odd e = pow3h b (e-1) (acc*b)
28
| otherwise = pow3h (b*b) (quot e 2) acc
29
30
-- Aufgabe 1.4
31
-- Suche größte natürliche Zahl x, sodass x^e <= r
32
-- Prinzipiell könnte e auch Double sein, aber wenn x und e
33
-- natürliche Zahlen sind, könnte man o.B.d.A r abrunden.
34
root :: Int -> Int -> Int
35
root e r = rootH 0 r
36
where rootH a b
37
| b-a == 1 = a
38
| floor (pow1 (fromIntegral(quot (a+b) 2)) e) <= r = rootH (quot (a+b) 2) b
39
| otherwise = rootH a (quot (a+b) 2)
40
41
-- Aufgabe 1.5: Primzahlcheck
42
isPrime :: Integer -> Bool
43
isPrime 0 = False
44
isPrime 1 = False
45
isPrime x = not (hasDivisor (root 2 x) 2)
46
where hasDivisor upperBound i
47
| i > upperBound = False
48
| mod x i == 0 = True
49
| otherwise = hasDivisor upperBound (i+1)
50
51