HITACM1006 - Weird Clock

5 篇文章 0 订阅
2 篇文章 0 订阅
问题描述
  • 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)x0(mod60)
  • 换算之后等价于: ( 1 + d ) x ≡ 0 ( m o d 60 / g c d ( 60 , s ) (1+d)^x\equiv0(mod60/gcd(60,s) (1+d)x0(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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值