proxygen
sample1.h File Reference

Go to the source code of this file.

Functions

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

Function Documentation

int Factorial ( int  n)

Definition at line 37 of file sample1.cc.

References i.

Referenced by TEST(), and TEST_F().

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

Definition at line 47 of file sample1.cc.

References i.

Referenced by TEST(), and TEST_F().

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 squre 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 }