Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
check_prime.cpp File Reference

Reduced all possibilities of a number which cannot be prime. Eg: No even number, except 2 can be a prime number, hence we will increment our loop with i+6 jumping and check for i or i+2 to be a factor of the number; if it's a factor then we will return false otherwise true after the loop terminates at the terminating condition which is (i*i<=num) More...

#include <cassert>
#include <iostream>
Include dependency graph for check_prime.cpp:

Functions

template<typename T >
bool is_prime (T num)
 for IO operations More...
 
int main ()
 

Detailed Description

Reduced all possibilities of a number which cannot be prime. Eg: No even number, except 2 can be a prime number, hence we will increment our loop with i+6 jumping and check for i or i+2 to be a factor of the number; if it's a factor then we will return false otherwise true after the loop terminates at the terminating condition which is (i*i<=num)

Copyright 2020

Author
omkarlanghe

A simple program to check if the given number if prime or not.

Function Documentation

◆ is_prime()

template<typename T >
bool is_prime ( num)

for IO operations

for assert Function to check if the given number is prime or not.

Parameters
numnumber to be checked.
Returns
if number is prime, it returns @ true, else it returns @ false.
24 {
25 bool result = true;
26 if (num <= 1) {
27 return false;
28 } else if (num == 2 || num == 3) {
29 return true;
30 } else if ((num % 2) == 0 || num % 3 == 0) {
31 return false;
32 } else {
33 for (T i = 5; (i * i) <= (num); i = (i + 6)) {
34 if ((num % i) == 0 || (num % (i + 2) == 0)) {
35 result = false;
36 break;
37 }
38 }
39 }
40 return (result);
41}
uint64_t result(uint64_t n)
Definition: fibonacci_sum.cpp:76

◆ main()

int main ( void  )

Main function

46 {
47 // perform self-test
48 assert(is_prime(50) == false);
49 assert(is_prime(115249) == true);
50
51 int num = 0;
52 std::cout << "Enter the number to check if it is prime or not" << std::endl;
53 std::cin >> num;
54 bool result = is_prime(num);
55 if (result) {
56 std::cout << num << " is a prime number" << std::endl;
57 } else {
58 std::cout << num << " is not a prime number" << std::endl;
59 }
60
61 return 0;
62}
bool is_prime(T num)
for IO operations
Definition: check_prime.cpp:24
T endl(T... args)
Here is the call graph for this function: