F´ Flight Software - C/C++ Documentation
A framework for building embedded system applications to NASA flight quality standards.
Algorithms.cpp
Go to the documentation of this file.
1 // ======================================================================
2 // \title Algorithms.cpp
3 // \author sjsreehari
4 // \brief cpp file for general-purpose mathematical algorithms
5 //
6 // \copyright
7 // Copyright (C) 2026 California Institute of Technology.
8 // ALL RIGHTS RESERVED. United States Government Sponsorship
9 // acknowledged.
10 // ======================================================================
11 
12 #include <Fw/Types/Assert.hpp>
13 #include <Utils/Algorithms.hpp>
14 #include <limits>
15 
16 namespace Utils {
17 namespace Algorithms {
18 
20  const FwSizeType maxIterations = static_cast<FwSizeType>(std::numeric_limits<FwSizeType>::digits) * 2;
21  for (FwSizeType i = 0; (i < maxIterations) && (b != 0); i++) {
22  FwSizeType temp = b;
23  b = a % b;
24  a = temp;
25  }
26  FW_ASSERT(b == 0);
27  return a;
28 }
29 
31  FW_ASSERT(a != 0);
32  FW_ASSERT(b != 0);
33  const FwSizeType g = gcd(a, b);
34  const FwSizeType a_div_g = a / g;
35  // Ensure that lcm will not overflow
36  FW_ASSERT((std::numeric_limits<FwSizeType>::max() / b) >= a_div_g, static_cast<FwAssertArgType>(a),
37  static_cast<FwAssertArgType>(b));
38  return a_div_g * b;
39 }
40 
41 } // namespace Algorithms
42 } // namespace Utils
PlatformSizeType FwSizeType
FwSizeType lcm(FwSizeType a, FwSizeType b)
Calculate the least common multiple of two numbers Asserts that a != 0, b != 0, and that the calculat...
Definition: Algorithms.cpp:30
FwSizeType gcd(FwSizeType a, FwSizeType b)
Calculate the greatest common divisor of two numbers using the Euclidean algorithm.
Definition: Algorithms.cpp:19
#define FW_ASSERT(...)
Definition: Assert.hpp:14