问题描述
-
A weird clock marked from 0 to 59 has only a minute hand. It won’t move until a special coin is thrown into its box. There are different kinds of coins as your options. However once you make your choice, you cannot use any other kind. There are infinite number of coins of each kind, each marked with a number d ( 0 <= 1000 ), meaning that this coin will make the minute hand move d times clockwise the current time. For example, if the current time is 45, and d = 2. Then the minute hand will move clockwise 90 minutes and will be pointing to 15.
-
Now you are given the initial time s ( 0 <= s <= 59 ) and the coin’s type d. Write a program to find the minimum number of d-coins needed to turn the minute hand back to 0.
-
input
There are several tests. Each test occupies a line containing two positive integers s and d.
The input is finished by a line containing 0 0.
- output
For each test print in a single line the minimum number of coins needed. If it is impossible to turn the hand back to 0, output “Impossible”. - example
输入:30 1
输出 1
分析
- 输入 s, d,每一次操作即为:s+ s*d,求能够经过数次操作之后到达0处.到达0处即: s ( 1 + d ) x ≡ 0 ( m o d 60 ) s(1+d)^x\equiv0(mod60) s(1+d)x≡0(mod60)
- 换算之后等价于: ( 1 + d ) x ≡ 0 ( m o d 60 / g c d ( 60 , s ) (1+d)^x\equiv0(mod60/gcd(60,s) (1+d)x≡0(mod60/gcd(60,s)
- 因为60 = 2 * 2 * 3 * 5,则1+d=2/3/5,且60/gcd(60,s) = 2/3/5/4时方程有解.可能的解有0,1,2,Impossible.
- 通过1+d的值和 1 + d , ( 1 + d ) 2 1+d,(1+d)^2 1+d,(1+d)2能否整除 60 / g c d ( 60 , s ) 60/gcd(60,s) 60/gcd(60,s),可求得结果.
代码
#include <stdio.h>
int gcd(int a,int b)
{///递归求最大公约数 欧几里得算法
if(a%b == 0)
return b;
else
return gcd(b,a%b);
}
int main()
{
int s,d;
while(scanf("%d %d",&s,&d)==2){
if(s==0&&d==0)
break;
if(s==0){
printf("0\n");
continue;
}
s=60/gcd(60,s);
if((d+1)%s ==0){
printf("1\n");
}else if((d+1)*(d+1)%s == 0){
printf("2\n");
}else{
printf("Impossible\n");
}
}
return 0;
}
优化之后
#include <stdio.h>
int main()
{
int s, p;
while(scanf("%d %d", &s, &p) == 2){
if((s == 0) && (p == 0)){
return 0;
}else if((s == 0) && (p != 0)){
printf("0\n");
}else if(s*(p+1) % 60 == 0){
printf("1\n");
}else if(s*(p+1)*(p+1) % 60 == 0){
printf("2\n");
}else{
printf("Impossible\n");
}
}
return 0;
}