相对素数
Relatively Prime Numbers
本文关键字:相对 更新时间:2023-10-16
如何在c++中生成一个函数,以确定输入的两个数字是否相对素数(没有公共因子)?例如,"1,3"是有效的,但"2,4"则无效。
由于Jim Clay不小心的评论,Euclid的算法有六行代码:
bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
for ( ; ; ) {
if (!(a %= b)) return b == 1 ;
if (!(b %= a)) return a == 1 ;
}
}
更新添加:Omnifarious的回答让我感到困惑,他对gcd
函数进行了编程,因此:
constexpr unsigned int gcd(unsigned int const a, unsigned int const b)
{
return (a < b) ? gcd(b, a) : ((a % b == 0) ? b : gcd(b, a % b));
}
现在我们有了一个三行版本的RelativelyPrime:
bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
return (a<b) ? RelativelyPrime(b,a) : !(a%b) ? (b==1) : RelativelyPrime (b, a%b);
}
计算最大公分母的众多算法之一。
相关文章:
- 如何计算具有指定类型的表达式的相对精度和绝对精度
- 如何使用cppcheck处理半相对包含路径
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 使用哈希图进行相对排序
- 有没有办法保证析构函数的相对顺序?
- Windows 和 Linux 之间的相对路径分辨率差异?
- 为什么从具有较大阵列的 SIMD 内部函数中获得的相对加速比标量更大?
- MOVNTI 存储是否相对于由同一线程创建的其他 MOVNTI 存储重新排序?
- 如何获取 CMake 单元测试的相对路径?
- std::atomic 和 std::mutex 的相对性能
- 我如何知道字符串中字符相对于英文字母的位置值?
- 非静态成员引用必须相对于特定对象
- 如何在相对于观看方向的地形中移动
- CRTP相对于抽象类的优势
- 如何设置与其背景图像大小相对应的窗口大小?
- 专门用于"direct"函数类型(与函数指针类型相对)
- 当两个相等的双精度的相对比较不起作用时,我该怎么办?
- 互斥锁能否保护相对于特定指针的数据?
- Bazel:http_archive()中url的相对本地路径
- 如何使用 in C++ 访问相对父目录<filesystem>