51nod oj 1035 最长的循环节 简单数论


正整数k的倒数1/k,写为10进制的小数如果为无限循环小数,则存在一个循环节,求<=n的数中,倒数循环节长度最长的那个数,假如存在多个最优的答案,输出所有答案中最大的那个数。

1/6= 0.1(6) 循环节长度为1
1/7= 0.(142857) 循环节长度为6
1/9= 0.(1)  循环节长度为1
Input输入n(10 <= n <= 1000) Output输出<=n的数中倒数循环节长度最长的那个数 Sample Input
10
Sample Output
7

先打表打出1-1000每个数循环节
  循环节判断方法是如果  新余数  在之前的余数出现过   那么一定是有循环节  注意避免初始余数的操作

#include
#include
#include
#include
#include
#include
#include

using namespace std;

long long t;
long long n, a, b;
long long gcd(long long x, long long y)
{
	return y == 0 ? x : gcd(y, x%y);
}

long long extgcd(long long a, long long b, long long &x, long long &y)
{
	if (b == 0)
	{
		x = 1;y = 0;
		return a;
	}

	long long r = extgcd(b, a%b, x, y);

	long long t = x;
	x = y;
	y = t - a / b*y;

	return r;
}


int ans[1010] = {0};


int main()
{

	ans[1] = 0;

	for (int i = 2;i < 1001;i++)
	{
		int vis[1010] = { 0 };

		int s = 1;
		
		int key = 1;
		while (s != 0)
		{

			if (vis[s] != 0)
			{
				ans[i] = key - vis[s];
				break;
			}

			vis[s] = key++;
			s = (s * 10) % i;
		}
		//ans[i] = max(ans[i - 1], ans[i]);
	}

	int n;
	scanf("%d", &n);
	int maxloc = 1;
	for (int i = 1;i <= n;i++)
	{
		if (ans[i] >= ans[maxloc])
			maxloc = i;
	}
	printf("%d\n", maxloc);
	return 0;
}


你可能感兴趣的:(数论)