Wire Sysio Wire Sysion 1.0.0
Loading...
Searching...
No Matches
sample1.cc File Reference
#include "sample1.h"
Include dependency graph for sample1.cc:

Go to the source code of this file.

Functions

int Factorial (int n)
 
bool IsPrime (int n)
 

Function Documentation

◆ Factorial()

int Factorial ( int n)

Definition at line 37 of file sample1.cc.

37 {
38 int result = 1;
39 for (int i = 1; i <= n; i++) {
40 result *= i;
41 }
42
43 return result;
44}

◆ IsPrime()

bool IsPrime ( int n)

Definition at line 47 of file sample1.cc.

47 {
48 // Trivial case 1: small numbers
49 if (n <= 1) return false;
50
51 // Trivial case 2: even numbers
52 if (n % 2 == 0) return n == 2;
53
54 // Now, we have that n is odd and n >= 3.
55
56 // Try to divide n by every odd number i, starting from 3
57 for (int i = 3; ; i += 2) {
58 // We only have to try i up to the square root of n
59 if (i > n/i) break;
60
61 // Now, we have i <= n/i < n.
62 // If n is divisible by i, n is not prime.
63 if (n % i == 0) return false;
64 }
65
66 // n has no integer factor in the range (1, n), and thus is prime.
67 return true;
68}