66 lines
1.8 KiB
C++
66 lines
1.8 KiB
C++
#include <iostream>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <cmath>
|
|
|
|
// use generics for a reusable method
|
|
template <typename number>
|
|
std::string create_overflow() {
|
|
number next = 2;
|
|
number valid = 0;
|
|
number iter = 0;
|
|
|
|
while(true) {
|
|
next = next * 2;
|
|
if(valid > next) {
|
|
std::string message = typeid(number).name();
|
|
message += " overflow occurred: 2**" + std::to_string(iter) + " = " + std::to_string(next);
|
|
message += " should be bigger as 2**" + std::to_string(iter - 1) + " != " + std::to_string(valid);
|
|
return message;
|
|
}
|
|
iter++; valid = next;
|
|
}
|
|
}
|
|
|
|
std::vector<bool> sieve_of_eratosthenes(int limit) {
|
|
// avoid edge cases limit=0 or limit=1
|
|
int length = limit + 2;
|
|
|
|
// preparation of a bool vector
|
|
std::vector<bool> primes(length, true);
|
|
primes[0] = false;
|
|
primes[1] = false;
|
|
|
|
// calculate sieve
|
|
for(int i = 2; i <= std::sqrt(limit); i++) {
|
|
if(primes[i]) {
|
|
for(int p = i * i; p <= limit; p += i) {
|
|
primes[p] = false;
|
|
}
|
|
}
|
|
}
|
|
return primes;
|
|
}
|
|
|
|
/*
|
|
* Anmerkung:
|
|
* Ich mag es nicht wirklich Pointer in C++ zu benutzen. Deshalb verwende ich die Klassen std::string und std::vector
|
|
* um zu verhindern, dass die Funktionen bool* bzw. char* pointer ausgeben müssen.
|
|
*/
|
|
int main() {
|
|
std::cout << create_overflow<short>() << std::endl;
|
|
std::cout << create_overflow<int>() << std::endl;
|
|
std::cout << create_overflow<long>() << std::endl;
|
|
|
|
int limit = 100;
|
|
std::vector<bool> primes = sieve_of_eratosthenes(limit);
|
|
std::cout << "Prime numbers up to " << limit << " are: ";
|
|
for (int i = 0; i < limit; ++i) {
|
|
if (primes[i]) {
|
|
std::cout << i << " ";
|
|
}
|
|
}
|
|
|
|
std::cout << std::endl;
|
|
return 0;
|
|
} |