Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Program: prime2.cpp // Test if a given natural number is prime. #include #include int main () { // Input unsigned int n; std::cout << "Test if n>1 is prime for n =? "; std::cin >> n; // Computation: test possible divisors d up to sqrt(n) const unsigned int bound = (unsigned int)(std::sqrt(n)); unsigned int d; for (d = 2; d <= bound && n % d != 0; ++d); // Output if (d <= bound) // d is a divisor of n in {2,...,[sqrt(n)]} std::cout << n << " = " << d << " * " << n / d << ".\n"; else // no proper divisor found std::cout << n << " is prime.\n"; return 0; }