hdu2522

A simple problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2786    Accepted Submission(s): 979


Problem Description
Zty很痴迷数学问题.。一天,yifenfei出了个数学题想难倒他,让他回答1 / n。但Zty却回答不了^_^. 请大家编程帮助他.
 
Input
第一行整数T,表示测试组数。后面T行,每行一个整数 n (1<=|n|<=10^5).
 
Output
输出1/n. (是循环小数的,只输出第一个循环节).
 
Sample Input
4
2
3
7
168
 
Sample Output
0.5
0.3
0.142857
0.005952380
 
思路:除法的本质,如果相除过程中,余数重复出现的时候,表示循环节出现了
代码:
 
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
    int a[100000],hash[100000];
    int t,m,b,cnt,n,i;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        if(n<0)
        {
            printf("-");
            n*=-1;
        }
        if(n==1)
        {
            printf("1 ");
        }
        else
        {
            b=1;
            cnt=0;
            memset(hash,0,sizeof(hash));
            hash[1]=1;
            while(b)
            {
                b*=10;
                a[cnt++]=b/n;
                b%=n;
                if(hash[b])
                    break;
                hash[b]=1;
            }
            printf("0.");
            for(i=0; i<cnt; i++)
                printf("%d",a[i]);
            printf(" ");
        }
    }
    return 0;
}
 
 
原文地址:https://www.cnblogs.com/lxm940130740/p/3442116.html