Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
math Namespace Reference

for std::rand More...

Classes

struct  Point
 

Functions

double approximate_pi (const std::vector< Point > &pts)
 
template<typename T >
square_area (T length)
 area of a square (l * l) More...
 
template<typename T >
rect_area (T length, T width)
 area of a rectangle (l * w) More...
 
template<typename T >
triangle_area (T base, T height)
 area of a triangle (b * h / 2) More...
 
template<typename T >
circle_area (T radius)
 area of a circle (pi More...
 
template<typename T >
parallelogram_area (T base, T height)
 area of a parallelogram (b * h) More...
 
template<typename T >
cube_surface_area (T length)
 surface area of a cube ( 6 * (l More...
 
template<typename T >
sphere_surface_area (T radius)
 surface area of a sphere ( 4 * pi * r^2) More...
 
template<typename T >
cylinder_surface_area (T radius, T height)
 surface area of a cylinder (2 * pi * r * h + 2 * pi * r^2) More...
 
double integral_approx (double lb, double ub, const std::function< double(double)> &func, double delta=.0001)
 Computes integral approximation. More...
 
void test_eval (double approx, double expected, double threshold)
 Wrapper to evaluate if the approximated value is within .XX% threshold of the exact value. More...
 
uint64_t largestPower (uint32_t n, const uint16_t &p)
 Function to calculate largest power. More...
 
uint64_t lcmSum (const uint16_t &num)
 
bool magic_number (const uint64_t &n)
 
uint64_t power (uint64_t a, uint64_t b, uint64_t c)
 This function calculates a raised to exponent b under modulo c using modular exponentiation. More...
 
template<class T >
n_choose_r (T n, T r)
 This is the function implementation of \( \binom{n}{r} \). More...
 
void power_of_two (int n)
 Function to test above algorithm. More...
 
uint64_t binomialCoeffSum (uint64_t n)
 
template<typename T >
cube_volume (T length)
 The volume of a cube More...
 
template<typename T >
rect_prism_volume (T length, T width, T height)
 The volume of a rectangular prism. More...
 
template<typename T >
cone_volume (T radius, T height, double PI=3.14)
 The volume of a cone More...
 
template<typename T >
triangle_prism_volume (T base, T height, T depth)
 The volume of a triangular prism. More...
 
template<typename T >
pyramid_volume (T length, T width, T height)
 The volume of a pyramid More...
 
template<typename T >
sphere_volume (T radius, double PI=3.14)
 The volume of a sphere More...
 
template<typename T >
cylinder_volume (T radius, T height, double PI=3.14)
 The volume of a cylinder More...
 

Detailed Description

for std::rand

for std::cin and std::cout

for std::cout

for io operations

Evaluate recurrence relation using matrix exponentiation.

for assert

Math algorithms.

for std::vector

for IO operations

for M_PI definition and pow()

for IO operations for std::vector

Mathematical algorithms

for assert for uint16_t datatype for IO operations

Mathematical algorithms

for assert for int32_t type for atoi

Mathematical algorithms

for assert for std::cin and std::cout

Mathematical algorithms

for assert for mathematical functions for passing in functions

Mathematical functions

for math functions for fixed size data types for time to initialize rng for function pointers for std::cout for random number generation for std::vector

for std::cin and std::cout

Mathematical algorithms

Given a recurrence relation; evaluate the value of nth term. For e.g., For fibonacci series, recurrence series is f(n) = f(n-1) + f(n-2) where f(0) = 0 and f(1) = 1. Note that the method used only demonstrates recurrence relation with one variable (n), unlike nCr problem, since it has two (n, r)

Algorithm

This problem can be solved using matrix exponentiation method.

See also
here for simple number exponentiation algorithm or explaination here.
Author
Ashish Daulatabad for assert for IO operations for std::vector STL

Mathematical algorithms

for assert

Mathematical algorithms

for std::is_equal, std::swap for assert for IO operations

Mathematical algorithms

for assert for io operations

Mathematical algorithms

Mathematical algorithms

for assert for std::pow for std::uint32_t

Mathematical algorithms

Function Documentation

◆ approximate_pi()

double math::approximate_pi ( const std::vector< Point > &  pts)

This function use the points pts (drawn at random) to return an estimate of the number π using the given points

Parameters
ptsEach item of pts contains a point. A point is represented by a structure containing exactly two numbers, respectively x and y such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1. pts always contains at least one item
Returns
an estimate of the number π
35 {
36 /**
37 * This function use the points pts (drawn at random) to return an estimate of the number π using the given points
38 * @param pts Each item of pts contains a point. A point is represented by a structure containing exactly
39 * two numbers, respectively x and y such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1.
40 * pts always contains at least one item
41 * @return an estimate of the number π
42 */
43 {
44 int count =0; // Points in cercle
45 for(Point p:pts)
46 if(p.x * p.x + p.y*p.y <= 1)
47 ++count;
48
49 return 4.0*count/pts.size();
50 }
51 }
Definition: approximate_pi.cpp:30

◆ binomialCoeffSum()

uint64_t math::binomialCoeffSum ( uint64_t  n)

Function to calculate sum of binomial coefficients

Parameters
nnumber
Returns
Sum of binomial coefficients of number
26 {
27 // Calculating 2^n
28 return (1 << n);
29}

◆ circle_area()

template<typename T >
T math::circle_area ( radius)

area of a circle (pi

  • r^2)
    Parameters
    radiusis the radius of the circle
    Returns
    area of the circle
63 {
64 return M_PI * pow(radius, 2);
65}

◆ cone_volume()

template<typename T >
T math::cone_volume ( radius,
height,
double  PI = 3.14 
)

The volume of a cone

Parameters
radiusThe radius of the base circle
heightThe height of the cone
PIThe definition of the constant PI
Returns
The volume of the cone
53 {
54 return std::pow(radius, 2) * PI * height / 3;
55}
int height(node *root)
Definition: avltree.cpp:31
T pow(T... args)
Here is the call graph for this function:

◆ cube_surface_area()

template<typename T >
T math::cube_surface_area ( length)

surface area of a cube ( 6 * (l

  • l))
    Parameters
    lengthis the length of the cube
    Returns
    surface area of the cube
86 {
87 return 6 * length * length;
88}

◆ cube_volume()

template<typename T >
T math::cube_volume ( length)

The volume of a cube

Parameters
lengthThe length of the cube
Returns
The volume of the cube
28 {
29 return std::pow(length, 3);
30}
Here is the call graph for this function:

◆ cylinder_surface_area()

template<typename T >
T math::cylinder_surface_area ( radius,
height 
)

surface area of a cylinder (2 * pi * r * h + 2 * pi * r^2)

Parameters
radiusis the radius of the cylinder
heightis the height of the cylinder
Returns
surface area of the cylinder
109 {
110 return 2 * M_PI * radius * height + 2 * M_PI * pow(radius, 2);
111}
Here is the call graph for this function:

◆ cylinder_volume()

template<typename T >
T math::cylinder_volume ( radius,
height,
double  PI = 3.14 
)

The volume of a cylinder

Parameters
radiusThe radius of the base circle
heightThe height of the cylinder
PIThe definition of the constant PI
Returns
The volume of the cylinder
103 {
104 return PI * std::pow(radius, 2) * height;
105}
Here is the call graph for this function:

◆ integral_approx()

double math::integral_approx ( double  lb,
double  ub,
const std::function< double(double)> &  func,
double  delta = .0001 
)

Computes integral approximation.

Parameters
lblower bound
ubupper bound
funcfunction passed in
delta
Returns
integral approximation of function from [lb, ub]
33 {
34 double result = 0;
35 uint64_t numDeltas = static_cast<uint64_t>((ub - lb) / delta);
36 for (int i = 0; i < numDeltas; i++) {
37 double begin = lb + i * delta;
38 double end = lb + (i + 1) * delta;
39 result += delta * (func(begin) + func(end)) / 2;
40 }
41 return result;
42}

◆ largestPower()

uint64_t math::largestPower ( uint32_t  n,
const uint16_t &  p 
)

Function to calculate largest power.

Parameters
nnumber
pprime number
Returns
largest power
27 {
28 // Initialize result
29 int x = 0;
30
31 // Calculate result
32 while (n)
33 {
34 n /= p;
35 x += n;
36 }
37 return x;
38 }

◆ lcmSum()

uint64_t math::lcmSum ( const uint16_t &  num)

Function to compute sum of euler totients in sumOfEulerTotient vector

Parameters
numinput number
Returns
int Sum of LCMs, i.e. ∑LCM(i, num) from i = 1 to num
29 {
30 uint64_t i = 0, j = 0;
31 std::vector<uint64_t> eulerTotient(num + 1);
32 std::vector<uint64_t> sumOfEulerTotient(num + 1);
33
34 // storing initial values in eulerTotient vector
35 for (i = 1; i <= num; i++) {
36 eulerTotient[i] = i;
37 }
38
39 // applying totient sieve
40 for (i = 2; i <= num; i++) {
41 if (eulerTotient[i] == i) {
42 for (j = i; j <= num; j += i) {
43 eulerTotient[j] = eulerTotient[j] / i;
44 eulerTotient[j] = eulerTotient[j] * (i - 1);
45 }
46 }
47 }
48
49 // computing sum of euler totients
50 for (i = 1; i <= num; i++) {
51 for (j = i; j <= num; j += i) {
52 sumOfEulerTotient[j] += eulerTotient[i] * i;
53 }
54 }
55
56 return ((sumOfEulerTotient[num] + 1) * num) / 2;
57}

◆ magic_number()

bool math::magic_number ( const uint64_t &  n)

Function to check if the given number is magic number or not.

Parameters
nnumber to be checked.
Returns
if number is a magic number, returns true, else false.
32 {
33 if (n <= 0) {
34 return false;
35 }
36 // result stores the modulus of @param n with 9
37 uint64_t result = n % 9;
38 // if result is 1 then the number is a magic number else not
39 if (result == 1) {
40 return true;
41 } else {
42 return false;
43 }
44}

◆ n_choose_r()

template<class T >
T math::n_choose_r ( n,
r 
)

This is the function implementation of \( \binom{n}{r} \).

We are calculating the ans with iterations instead of calculating three different factorials. Also, we are using the fact that \( \frac{n!}{r! (n-r)!} = \frac{(n - r + 1) \times \cdots \times n}{1 \times \cdots \times r} \)

Template Parameters
TOnly for integer types such as long, int_64 etc
Parameters
n\( n \) in \( \binom{n}{r} \)
r\( r \) in \( \binom{n}{r} \)
Returns
ans \( \binom{n}{r} \)
35 {
36 if (r > n / 2) {
37 r = n - r; // Because of the fact that nCr(n, r) == nCr(n, n - r)
38 }
39 T ans = 1;
40 for (int i = 1; i <= r; i++) {
41 ans *= n - r + i;
42 ans /= i;
43 }
44 return ans;
45}
ll ans(ll n)
Definition: matrix_exponentiation.cpp:91
Here is the call graph for this function:

◆ parallelogram_area()

template<typename T >
T math::parallelogram_area ( base,
height 
)

area of a parallelogram (b * h)

Parameters
baseis the length of the bottom side of the parallelogram
heightis the length of the tallest point in the parallelogram
Returns
area of the parallelogram
75 {
76 return base * height;
77}
Here is the call graph for this function:

◆ power()

uint64_t math::power ( uint64_t  a,
uint64_t  b,
uint64_t  c 
)

This function calculates a raised to exponent b under modulo c using modular exponentiation.

Parameters
ainteger base
bunsigned integer exponent
cinteger modulo
Returns
a raised to power b modulo c

Initialize the answer to be returned

Update a if it is more than or equal to c

In case a is divisible by c;

If b is odd, multiply a with answer

b must be even now

b = b/2

35 {
36 uint64_t ans = 1; /// Initialize the answer to be returned
37 a = a % c; /// Update a if it is more than or equal to c
38 if (a == 0) {
39 return 0; /// In case a is divisible by c;
40 }
41 while (b > 0) {
42 /// If b is odd, multiply a with answer
43 if (b & 1) {
44 ans = ((ans % c) * (a % c)) % c;
45 }
46 /// b must be even now
47 b = b >> 1; /// b = b/2
48 a = ((a % c) * (a % c)) % c;
49 }
50 return ans;
51}
Here is the call graph for this function:

◆ power_of_two()

void math::power_of_two ( int  n)

Function to test above algorithm.

Parameters
ndescription
Returns
void

This function finds whether a number is power of 2 or not

Parameters
nvalue for which we want to check prints the result, as "Yes, the number n is a power of 2" or "No, the number is not a power of 2" without quotes

result stores the bitwise and of n and n-1

36 {
37 /**
38 * This function finds whether a number is power of 2 or not
39 * @param n value for which we want to check
40 * prints the result, as "Yes, the number n is a power of 2" or
41 * "No, the number is not a power of 2" without quotes
42 */
43 /// result stores the
44 /// bitwise and of n and n-1
45 int result = n & (n - 1);
46 if (result == 0) {
47 std::cout << "Yes, the number " << n << " is a power of 2";
48 } else {
49 std::cout << "No, the number " << n << " is not a power of 2";
50 }
51}

◆ pyramid_volume()

template<typename T >
T math::pyramid_volume ( length,
width,
height 
)

The volume of a pyramid

Parameters
lengthThe length of the base shape (or base for triangles)
widthThe width of the base shape (or height for triangles)
heightThe height of the pyramid
Returns
The volume of the pyramid
80 {
81 return length * width * height / 3;
82}
Here is the call graph for this function:

◆ rect_area()

template<typename T >
T math::rect_area ( length,
width 
)

area of a rectangle (l * w)

Parameters
lengthis the length of the rectangle
widthis the width of the rectangle
Returns
area of the rectangle
40 {
41 return length * width;
42}

◆ rect_prism_volume()

template<typename T >
T math::rect_prism_volume ( length,
width,
height 
)

The volume of a rectangular prism.

Parameters
lengthThe length of the base rectangle
widthThe width of the base rectangle
heightThe height of the rectangular prism
Returns
The volume of the rectangular prism
41 {
42 return length * width * height;
43}
Here is the call graph for this function:

◆ sphere_surface_area()

template<typename T >
T math::sphere_surface_area ( radius)

surface area of a sphere ( 4 * pi * r^2)

Parameters
radiusis the radius of the sphere
Returns
surface area of the sphere
97 {
98 return 4 * M_PI * pow(radius, 2);
99}

◆ sphere_volume()

template<typename T >
T math::sphere_volume ( radius,
double  PI = 3.14 
)

The volume of a sphere

Parameters
radiusThe radius of the sphere
PIThe definition of the constant PI
Returns
The volume of the sphere
91 {
92 return PI * std::pow(radius, 3) * 4 / 3;
93}
Here is the call graph for this function:

◆ square_area()

template<typename T >
T math::square_area ( length)

area of a square (l * l)

Parameters
lengthis the length of the square
Returns
area of square
29 {
30 return length * length;
31}

◆ test_eval()

void math::test_eval ( double  approx,
double  expected,
double  threshold 
)

Wrapper to evaluate if the approximated value is within .XX% threshold of the exact value.

Parameters
approxaprroximate value
exactexpected value
thresholdvalues from [0, 1)
51 {
52 assert(approx >= expected * (1 - threshold));
53 assert(approx <= expected * (1 + threshold));
54}

◆ triangle_area()

template<typename T >
T math::triangle_area ( base,
height 
)

area of a triangle (b * h / 2)

Parameters
baseis the length of the bottom side of the triangle
heightis the length of the tallest point in the triangle
Returns
area of the triangle
52 {
53 return base * height / 2;
54}
Here is the call graph for this function:

◆ triangle_prism_volume()

template<typename T >
T math::triangle_prism_volume ( base,
height,
depth 
)

The volume of a triangular prism.

Parameters
baseThe length of the base triangle
heightThe height of the base triangles
depthThe depth of the triangular prism (the height of the whole prism)
Returns
The volume of the triangular prism
67 {
68 return base * height * depth / 2;
69}
Here is the call graph for this function: