循環數的判斷(60位以內)

循環數是一個整數,滿足乘連續的若干個數後各位發生循環。最廣爲人知的循環數是142857.其循環如下:

142857 × 1 = 142857

142857 × 2 = 285714

142857 × 3 = 428571

142857 × 4 = 571428

142857 × 5 = 714285

142857 × 6 = 857142

因爲時間原因代碼沒有優化之類的委屈。以後有時間我會把優化後的放上來的

#include<iostream>
#include<string>
using namespace std;
const int size = 60;

int main()
{
	
	string str;
	while (cin >> str)
	{
		int num[size] = { 0 }, num_temp[size * 2] = { 0 };
		int str_length = str.size();
		int locate = size - str_length;

		for (int f = 0; f < str_length; f++)
		{

			num[size - 1 - f] = str[str_length - 1 - f] - '0';
			num_temp[str_length - 1 - f] = str[str_length - 1 - f] - '0';
			num_temp[2 * str_length - 1 - f] = str[str_length - 1 - f] - '0';
		}
	
		int count = 1;
		for (int i = 2; i <= str_length; i++)
		{
			
			int lnum[size] = { 0 };
			for (int j = 0; j < str_length; j++)
			{
				lnum[size - 1 - j] += num[size - 1 - j] * i;
				if (lnum[size - 1 - j]>9)
				{
					lnum[size - 2 - j] += lnum[size - 1 - j] / 10;
					lnum[size - 1 - j] %= 10;
				}
			}    

			int k = 0,count_k=0;int count_l = 0;
			for (; k < str_length; k++)
			{
				if (lnum[locate] == num_temp[k])
				{
					int l = 0; 
					for (; l < str_length; l++)
					{
						if (lnum[locate + l] != num_temp[k + l])break;
					}
					if (l == str_length)
					{
						count_l++; break;
					}
				}
					
			}
			if (count_l == 1)
			{
				count++; continue;
			}
		}

		if (count == str_length)
		{
			cout << str << " is cyclic" << endl;
		}
		else
		{
			cout << str << " is not cyclic" << endl;
		}
	}
	return 0;
}

發佈了33 篇原創文章 · 獲贊 17 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章