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

原理见百度百科:欧几里得算法

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;
}


你可能感兴趣的:(求最大公约数(欧几里得算法))