求最大公约数(欧几里得算法)
2015-10-24 20:42
337 查看
原理见百度百科:欧几里得算法
int gcd(int a, int b)
{
if(a < b)
swap(a, b);
return b == 0 ? a : gcd(b, a % b);
}
用于编程珠玑第二章的向量旋转问题,重新写这个程序:
#include <iostream>
#include <string>
using namespace std;
void rotate(string &str, int i)
{
int strLen = str.size();
int numOfLoop = gcd(strLen, i);
for(int loop = 0; loop < numOfLoop; ++loop)
{
char tmp = str[loop];
int current = loop;
int next = loop + i;
while(next % strLen != loop)
{
str[current] = str[next];
current = (current + i) % strLen;
next = (next + i) % strLen;
}
str[current] = tmp;
}
}
int main() {
string str = "abcdefgh";
rotate(str, 4);
for(auto c : str)
cout << c;
cout << endl;
return 0;
}
int gcd(int a, int b)
{
if(a < b)
swap(a, b);
return b == 0 ? a : gcd(b, a % b);
}
用于编程珠玑第二章的向量旋转问题,重新写这个程序:
#include <iostream>
#include <string>
using namespace std;
void rotate(string &str, int i)
{
int strLen = str.size();
int numOfLoop = gcd(strLen, i);
for(int loop = 0; loop < numOfLoop; ++loop)
{
char tmp = str[loop];
int current = loop;
int next = loop + i;
while(next % strLen != loop)
{
str[current] = str[next];
current = (current + i) % strLen;
next = (next + i) % strLen;
}
str[current] = tmp;
}
}
int main() {
string str = "abcdefgh";
rotate(str, 4);
for(auto c : str)
cout << c;
cout << endl;
return 0;
}
相关文章推荐
- 阅读《大道至简》有感
- 图像、帧、片、NALU
- 参加公司招聘笔试有感
- WIFI项目--Android 获取本机IP(wifi下),子网掩码,网关,dns等信息
- hdu1532 网络流入门 dinic
- vim 兼容性的bug --softtabstops
- php中双$$与多$$
- “利益相关者”课堂讨论电子版
- 浏览器到服务器的请求响应过程时序图
- 拥抱未来吧——第二日
- sensor调试过程HAL层数据不能被转移到app
- [C++] How to prevent memory leaks
- 测试实习生面试题
- 用宏换参
- 谈java多线程方式刷数据的一点建议
- oh my zsh
- 利用Visio转换成pdf图形时的注意事项
- 利用LruCache和DiskLruCache实现图片异步下载
- [C++] 2D Array's memory allocation
- hdu 3943 数位dp+二分