How to write a C Program Algorithm:
- Divide numerator by denominator until remainder = 0
- or it makes a loop (a remainder appears twice).
- Use array to mark position of a remainder.
-
/**
-
Algorithm:
-
Divide numerator by denominator until remainder = 0
-
or it makes a loop (a remainder appears twice).
-
Use array to mark position of a remainder
-
*/
-
#include <cstdio>
-
-
int digits[100001];
-
int pos[100001];
-
//position of a remainder
-
-
int main() {
-
int numer, denom;
-
printf("Nhap tu so va mau so: ");
-
scanf("%d%d", &numer, &denom);
-
-
printf("%d", numer / denom);
-
//Division
-
numer %= denom;
-
if (numer == 0) return 0;
-
-
printf(".");
-
-
int at;
-
for(at = 1; numer != 0; ++at) {
-
if (pos[numer]) {
-
//A remainder appeared before so it makes a loop
-
for(int i = 1; i < pos[numer]; ++i) printf("%d", digits[i]);
-
//Before loop
-
-
printf("(");
-
//A loop goes here
-
for(int i = pos[numer]; i < at; ++i) printf("%d", digits[i]);
-
printf(")");
-
break;
-
}
-
//remainder did not appear before
-
pos[numer] = at;
-
numer *= 10;
-
digits[at] = numer / denom;
-
numer %= denom;
-
if (numer == 0) {
-
//this fraction has no loop
-
for(int i = 1; i <= at; ++i) printf("%d\n", digits[i]);
-
break;
-
}
-
}
-
return 0;
-
}
- /**
- Algorithm:
- Divide numerator by denominator until remainder = 0
- or it makes a loop (a remainder appears twice).
- Use array to mark position of a remainder
- */
- #include <cstdio>
- int digits[100001];
- int pos[100001];
- //position of a remainder
- int main() {
- int numer, denom;
- printf("Nhap tu so va mau so: ");
- scanf("%d%d", &numer, &denom);
- printf("%d", numer / denom);
- //Division
- numer %= denom;
- if (numer == 0) return 0;
- printf(".");
- int at;
- for(at = 1; numer != 0; ++at) {
- if (pos[numer]) {
- //A remainder appeared before so it makes a loop
- for(int i = 1; i < pos[numer]; ++i) printf("%d", digits[i]);
- //Before loop
- printf("(");
- //A loop goes here
- for(int i = pos[numer]; i < at; ++i) printf("%d", digits[i]);
- printf(")");
- break;
- }
- //remainder did not appear before
- pos[numer] = at;
- numer *= 10;
- digits[at] = numer / denom;
- numer %= denom;
- if (numer == 0) {
- //this fraction has no loop
- for(int i = 1; i <= at; ++i) printf("%d\n", digits[i]);
- break;
- }
- }
- return 0;
- }