Summary Files Commits Branches @commit @diff @stats
path: root / Year 1 / Object-oriented Programming / 07-Practice-05.04.2022 / NumberHelpers.cpp
diff options
context:
space:
mode:
Commit30420a6ea65aa58389b9ffa0ba67130de376c079 (patch)
Author
 Syndamia <kamen.d.mladenov@protonmail.com>
2022-04-06 10:29:54 +0300
Committer
 Syndamia <kamen.d.mladenov@protonmail.com>
2022-04-06 10:29:54 +0300
Files12981a8607166b51b9dbbee5ab8e1d965bff509b /Year 1/Object-oriented Programming/07-Practice-05.04.2022/NumberHelpers.cpp
uni-projects-30420a6ea65aa58389b9ffa0ba67130de376c079.tar
uni-projects-30420a6ea65aa58389b9ffa0ba67130de376c079.tar.gz
uni-projects-30420a6ea65aa58389b9ffa0ba67130de376c079.zip
Parent2cf8d711c3dd110555c16913941f865841aa3175 (diff)
Implemented overall functionality for yesterdays practice exercise
1 files changed, 35 insertions, 0 deletions
-rw-r--r--Year 1/Object-oriented Programming/07-Practice-05.04.2022/NumberHelpers.cpp35
diff --git a/Year 1/Object-oriented Programming/07-Practice-05.04.2022/NumberHelpers.cpp b/Year 1/Object-oriented Programming/07-Practice-05.04.2022/NumberHelpers.cpp
new file mode 100644
index 0000000..d7843b4
--- /dev/null
+++ b/Year 1/Object-oriented Programming/07-Practice-05.04.2022/NumberHelpers.cpp
@@ -0,0 +1,35 @@
+#include "NumberHelpers.h"
+
+bool isEven(int x) {
+ return x % 2 == 0;
+}
+
+// The following functions are taken from my own Interval task solution
+
+bool isPowerOfTwo(int x)
+{
+ return x > 0 && // No (normal) power of 2 creates negatives or 0
+ (x & (x - 1)) == 0; // Thanks https://stackoverflow.com/a/600306/12036073, original implementation was a lot less efficient
+}
+
+bool isPrime(int num) // Forked from my own implementation - https://gitlab.com/Syndamia/algorithms/-/blob/master/C/IsPrime.c
+{
+ if (num < 0) num *= -1; // This is required, since we calculate sqrt(num)
+
+ if (num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13)
+ return true;
+
+ // A lot of numbers are divisible by these ones, so we're going to do a bit of simple optimization
+ if (num == 0 || num == 1 || num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num % 7 == 0 || num % 11 == 0 || num % 13 == 0)
+ return false;
+
+ // All primes follow the formula 6n +- 1 (where n >= 1). Since we've already checked up to 13, we're going to
+ // start with 18 - 1 = 17. Also using root of number to eliminate a lot of checks.
+ // Primary source: https://en.wikipedia.org/wiki/Primality_test#Simple_methods
+ for (int i = 18, root = sqrt(num); i - 1 <= root; i += 6)
+ {
+ if (num % (num - 1) == 0 || num % (num + 1) == 0)
+ return false;
+ }
+ return true;
+}