summaryrefslogtreecommitdiff
path: root/I_anno/Programmazione_2
diff options
context:
space:
mode:
authorSanto Cariotti <dcariotti24@gmail.com>2020-07-19 21:24:19 +0200
committerSanto Cariotti <dcariotti24@gmail.com>2020-07-19 21:24:19 +0200
commit3833c952f1dff3957bc423045df6d52c14a6db78 (patch)
treefd6b2a4ebb3fded7be43bce82aaac03912119b55 /I_anno/Programmazione_2
parent0c6faed1acb130ae5bbc572dc7194a263f1cca6c (diff)
chore: new algorithms
Diffstat (limited to 'I_anno/Programmazione_2')
-rw-r--r--I_anno/Programmazione_2/algorithms/log.cc25
-rw-r--r--I_anno/Programmazione_2/algorithms/pow.cc34
-rw-r--r--I_anno/Programmazione_2/algorithms/sqrt.cc38
3 files changed, 97 insertions, 0 deletions
diff --git a/I_anno/Programmazione_2/algorithms/log.cc b/I_anno/Programmazione_2/algorithms/log.cc
new file mode 100644
index 0000000..1e49a2e
--- /dev/null
+++ b/I_anno/Programmazione_2/algorithms/log.cc
@@ -0,0 +1,25 @@
+#include<iostream>
+
+using namespace std;
+
+double log(double n) {
+ if(n <= 2) return 1.0;
+ return 1.0 + log(n/2);
+}
+
+int log2(double n) {
+ int a = 1;
+
+ while(n > 2) {
+ n /= 2;
+ ++a;
+ }
+
+ return a;
+}
+
+int main() {
+ for(int i = 0; i < 25; ++i)
+ cout << i << ' ' << log(i) << ' ' << log2(i) << endl;
+ return 0;
+}
diff --git a/I_anno/Programmazione_2/algorithms/pow.cc b/I_anno/Programmazione_2/algorithms/pow.cc
new file mode 100644
index 0000000..70f5b43
--- /dev/null
+++ b/I_anno/Programmazione_2/algorithms/pow.cc
@@ -0,0 +1,34 @@
+#include<iostream>
+
+using namespace std;
+
+int pow(int b, int e) {
+ if(e == 0) return 1;
+ int a = b;
+ int inc = b;
+ for(int i = 0; i < e-1; ++i) {
+ for(int j = 0; j < b-1; ++j) {
+ a+=inc;
+ }
+ inc = a;
+ }
+ return a;
+}
+
+int mul(int b, int e) {
+ if(e == 0) return 0;
+
+ return b+mul(b, e-1);
+}
+
+int pow2(int b, int e) {
+ if(e == 0) return 1;
+
+ return mul(b, pow(b, e-1));
+}
+
+int main() {
+ cout << pow(2, 5) << endl;
+ cout << pow2(2, 5) << endl;
+ return 0;
+}
diff --git a/I_anno/Programmazione_2/algorithms/sqrt.cc b/I_anno/Programmazione_2/algorithms/sqrt.cc
new file mode 100644
index 0000000..01d1079
--- /dev/null
+++ b/I_anno/Programmazione_2/algorithms/sqrt.cc
@@ -0,0 +1,38 @@
+#include<iostream>
+
+using namespace std;
+
+double abs(double n) {
+ if(n < 0) return -n;
+
+ return n;
+}
+
+
+double sq(int n) {
+ double x = n;
+ double y = 1;
+ while(x-y > 0.0000001) {
+ x = (x+y)/2;
+ y = n/x;
+ }
+ return x;
+}
+
+double sq2_n(double n, double a) {
+ if(abs(a*a - n) <= 0.000001) {
+ return a;
+ }
+
+ return sq2_n(n, (a+n/a)/2);
+}
+
+double sq2(int n) {
+ return sq2_n(n, n/2);
+}
+
+int main() {
+ cout << sq(81) << endl;
+ cout << sq2(81) << endl;
+ return 0;
+}