当前位置: 首页 > news >正文

常用基础算法程序

常用的基础算法程序

1.高位数逐位取出

逆序输出:

#include <iostream>
using namespace std;int main()
{int n;cin >> n;while (n){cout << n % 10;n /= 10;}return 0;
}

正序输出(使用递归):

#include <iostream>void get_first_digit(int num) {if(num < 10) {std::cout << num << " ";return;}get_first_digit(num / 10);std::cout << (num % 10) << " ";
}int main() {int num = 12345;get_first_digit(num);  // 输出:1 2 3 4 5return 0;
}

2.获取多位数位数

#include <iostream>
using namespace std;int main()
{int n;cin >> n;int cnt = 0;while (n){n /= 10;cnt++;}cout << cnt << endl;return 0;
}

3.求最大公约数

#include <iostream>
using namespace std;/// @brief Greatest Common Divisor
/// @param a
/// @param b
/// @return
int gcd(int a, int b)
{if (b == 0){return a;}else{return gcd(b, a % b);}
}int main()
{int a, b;cin >> a >> b;cout << gcd(a, b) << endl;return 0;
}

更推荐用循环写:

#include <iostream>
using namespace std;int main()
{int a, b;cin >> a >> b;int c = a % b;while (c){a = b;b = c;c = a % b;}cout << b << endl;return 0;
}

4.求最小公倍数

需要先实现最大公因数。

#include <iostream>
using namespace std;int main()
{int a, b;cin >> a >> b;cout << a * b / gcd(a, b) << endl;return 0;
}
http://www.zskr.cn/news/53589.html

相关文章:

  • 2025出国留学机构哪家强?5大靠谱品牌深度测评
  • Wavelet tree
  • Dify VS LangGraph
  • 详细介绍:pdf解析工具---Miner-u 本地部署记录
  • 使用Action表驱动代替switch…case语句
  • L11 RuoYi_数据分页的总条数分析
  • 2025最新江苏苏州、高邮、镇江方向(专线)物流、当日往返运输、配送中心、分拨中心服务商推荐:时效性高,线路可定制,提供仓储、供应链等物流全链条服务
  • c#json帮助类
  • 11.17 事务的隔离级别
  • 详细介绍:深度学习 计算机视觉 Kaggle(上):从理论殿堂起步 ——像素、特征与模型的进化之路
  • Web of Things (WoT) 物描述 2.0 首个公开工作草案发布
  • 图形渲染与 GPU 交互中的 C++ 性能优化技巧 - 教程
  • 罗盘
  • 计算机网络中最短帧长的概念
  • linux c 编译命令
  • linux c 线程编程
  • 容器网络虚拟化
  • CF1721F Matching Reduction
  • NSSCTF刷题日记
  • 详细介绍:UE4_Niagara基础实例—15、粒子发射器之间的通信
  • 2025年目前口碑好的继承官司律师律所有哪些,遗产继承律师事务所/北京最好的继承律师/婚姻律师事务所/继承律师/北京继承纠纷律师律所哪家强
  • 第一章 拓扑空间与连续映射
  • JOISC 口糊记录
  • 基于epoll的io复用管理,一种文件监听方案 2 - 教程
  • 重组蛋白科研试剂技术综述:结构特性、功能机制与实验体系应用
  • linux c 命令
  • taptap以官包模式下如何开展营销活动
  • Jupyter/IPython 魔法命令列表
  • 第29天(中等题 二分查找)
  • 题解:AtCoder ARC192D Fraction Line