Ultraviolet A 10555-dead fraction (number theory + infinite repeating decimals)

Source: Internet
Author: User
Ultraviolet A 10555-dead Fraction

Question Link

Given a repeating decimal point, the unit is uncertain. The decimal point is represented by a fraction with the minimum denominator.

Idea: Push a small Formula
A decimal point 0. aaaaabbb... is in the form of N/m, and a is an integer with a C digit, and B is a decimal part with a D digit.
So AAAAA. BBB... And aaaaabbb can be expressed as 10 respectively.C? (N/M) And 10C+D? (N/M)
The two methods are subtracted:AAAAABBB?AAAAA= (10C+D? 10C)(N/M)
Set n1 = aaaaabbb, n2 = AAAAA, M1 = 10C+D, M2 = 10C.
Therefore, N/m can be expressed as (N1-N2)/(M1-m2)

To solve this problem, calculate the positions of N1, N2, M1, and m2 respectively to indicate the scores and record the minimum denominator values.

Code:

#include <stdio.h>#include <string.h>char str[105];const long long INF = 0x3f3f3f3f3f3f3f;long long gcd(long long a, long long b) {    if (!b) return a;    return gcd(b, a % b);}void solve() {    int len = strlen(str) - 5;    for (int i = 0; i < len; i++)str[i] = str[i + 2];    long long n1 = 0, m1 = 1;    long long anszi, ansmu = INF;    for (int i = 0; i < len; i++) {n1 = n1 * 10 + str[i] - '0';m1 *= 10;    }    for (int i = 0; i < len; i++) {int n2 = 0, m2 = 1;for (int j = 0; j < i; j++) {    n2 = n2 * 10 + str[j] - '0';    m2 *= 10;}long long zi = n1 - n2, mu = m1 - m2;long long k = gcd(zi, mu);zi /= k; mu /= k;if (mu < ansmu) {    anszi = zi;    ansmu = mu;}    }    printf("%lld/%lld\n", anszi, ansmu);}int main() {    while (~scanf("%s", str) && strcmp(str, "0") != 0) {solve();    }    return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.