题解 | #将真分数分解为埃及分数#
将真分数分解为埃及分数
https://www.nowcoder.com/practice/e0480b2c6aa24bfba0935ffcca3ccb7b
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
void huajian(int* a, int* b)
{
if (*a == 1)
return;
for (int i = 2; i <= *a; i++)
{
if (*a % i == 0 && *b % i == 0)
{
*a = *a / i;
*b /= i;
huajian(a, b);
return;
}
}
}
int main()
{
char input[20] = { 0 };
scanf("%s", input);
int a, b;
sscanf(input, "%d/%d", &a, &b);
int res[20] = { 0 };
int place = 0;
huajian(&a, &b);
for (int i = 2; i < a * b; i++)
{
if (a == 1)
{
res[place++] = b;
break;
}
if (i * a > b)
{
res[place++] = i;
a = i * a - b;
b = b * i;
huajian(&a, &b);
}
}
printf("1/%d", res[0]);
if (place > 1)
{
for (int i = 1; i < place; i++)
printf("+1/%d", res[i]);
}
}
#include <stdio.h>
void huajian(int* a, int* b)
{
if (*a == 1)
return;
for (int i = 2; i <= *a; i++)
{
if (*a % i == 0 && *b % i == 0)
{
*a = *a / i;
*b /= i;
huajian(a, b);
return;
}
}
}
int main()
{
char input[20] = { 0 };
scanf("%s", input);
int a, b;
sscanf(input, "%d/%d", &a, &b);
int res[20] = { 0 };
int place = 0;
huajian(&a, &b);
for (int i = 2; i < a * b; i++)
{
if (a == 1)
{
res[place++] = b;
break;
}
if (i * a > b)
{
res[place++] = i;
a = i * a - b;
b = b * i;
huajian(&a, &b);
}
}
printf("1/%d", res[0]);
if (place > 1)
{
for (int i = 1; i < place; i++)
printf("+1/%d", res[i]);
}
}