首页 > 学院 > 开发设计 > 正文

算典03_习题_08_UVA-202

2019-11-08 03:04:39
字体:
来源:转载
供稿:网友

Repeating Decimals

题意

一个分数的小数形式一定是一个无限循环小数 现在要输出一个分数的无限循环小数,其最小循环节用括号括起来,同时输出最小的循环周期

题解

求出余数,每次存储余数*10/除数作为结果,而余数*10%除数则作为下一次的余数进行循环 记录这些余数的出现信息(值+是否出现过),直到某个余数再一次出现的时候,结束循环,得出一个循环节的长度 接着就只要考虑输出格式即可

#include <iostream>#include <cstdio>#include <algorithm>#include <cstring>using namespace std;const int maxn = 3e3 +5;#define met(a,b) memset(a, b, sizeof(a));int a, b, id;char s[maxn], str[] = {" = number of digits in repeating cycle"};int Div[maxn], dID;int main(){ #ifdef _LOCAL freopen("in.txt","r", stdin); #endif // _LOCAL while(scanf("%d%d", &a, &b) != EOF) { int c = a % b, res = 1; id = 0; met(Div, 0); dID = 1; while(!Div[c]){ if(c == 0){ s[id++] = '(';s[id++] = '0';s[id++] = ')'; break; } Div[c] = dID++; ++res; s[id++] = c*10 / b + '0'; c = c*10 % b; } s[id] = '/0'; PRintf("%d/%d = %d.", a, b, a/b); if(!c) printf("%s/n 1%s", s, str); else { for(int i = 0; i < min(50,id); ++i){ if(i == Div[c] - 1)printf("("); printf("%c", s[i]); } if(id >= 50) printf("..."); printf(")/n %d%s", res - Div[c], str); } printf("/n/n"); } return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表