您的位置:首页 > 其它

求最大公约数(欧几里得算法)

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: