Round and Round we go

/*
總時間限制: 1000ms 內存限制: 65536kB
描述
A cyclic number is an integer n digits in length which, when multiplied by any integer from 1 to n, yields a"cycle"of the digits of the original number. That is, if you consider the number after the last digit to "wrap around"back to the first digit, the sequence of digits in both numbers will be the same, though they may start at different positions.For example, the number 142857 is cyclic, as illustrated by the following table:
142857	*1	=	142857
142857	*2	=	285714
142857	*3	=	428571
142857	*4	=	571428
142857	*5	=	714285
142857	*6	=	857142
輸入
Write a program which will determine whether or not numbers are cyclic. The input file is a list of integers from 2 to 60 digits in length. (Note that preceding zeros should not be removed, they are considered part of the number and count in determining n. Thus, "01"is a two-digit number, distinct from "1" which is a one-digit number.)
輸出
For each input integer, write a line in the output indicating whether or not it is cyclic.
樣例輸入
142857
142856
142858
01
0588235294117647
樣例輸出
142857 is cyclic
142856 is not cyclic
142858 is not cyclic
01 is not cyclic
0588235294117647 is cyclic
來源
Greater New York 2001
*/
/*
程序編寫過程中主要思路如下:
分別將原數字與1到n相乘,再比較所得結果是否與源字符串相循環
故有函數大數乘法Multify(),Circle(),isRight()
其中大數乘法不太熟悉,debug了半天
另外判斷是否循環巧用了複製原字符兩遍再尋找字串的方法
*/
#include<iostream>
#include<cstring>
using namespace std;
char str[61];
char model[61];
int num[61];
char* Multify(char* str_,int n)
{
	memset(model,0,sizeof(model));
	int carry = 0,temp;
	memset(num,0,sizeof(num));
	int len = strlen(str_);
	for(int i = 0; i < len; ++i)
		num[i] = str_[len - 1 - i] - '0';
	for(int i = 0; i < len; ++i)
	{
		temp = num[i];
		num[i] =( num[i] * n + carry) % 10;
		carry = (temp * n + carry) /10;
	}
	if(num[len])
		for(int i = 0; i < len+1; ++i)
			model[i] = num[len-i] + '0';
	else
		for(int i = 0; i < len; ++i)
			model[i] = num[len-1-i] + '0';
	return model;
}
//判斷兩個字符串是否循環相等,首先在s內複製連續兩段s1,再在s內尋找s2,如果有s2,則證明可以循環
//此處用到了strstr函數
bool Circle(char* s1,char* s2)
{
	char s[200];
	strcpy(s,s1);
	strcat(s,s1);
	if(strstr(s,s2) != NULL)
		return true;
	return false;
}
bool isRight(char* str_)
{
	int len = strlen(str_);
	int i = 1;
	char* model_str;
	model_str = new char[len+1];
	model_str[len+1] = '\0';
	for(i = 1; i <= len; ++i)
	{
		strcpy(model_str,Multify(str_,i));
		if(Circle(str_,model_str) != true)
			return false;
	}
	return true;
}
int main()
{
	while(cin >> str)
	{
	   if(isRight(str))
		   cout << str << " is cyclic" << endl;
	   else
		   cout << str << " is not cyclic" << endl;
	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章