描述
In the 18th century, L. Euler invented a function he called sigma to study properties of whole numbers. He was interested
in comparing a positive number to the sum of its positive divisors. In this problem we extend Euler's function to fractions.
Given a positive rational number (i.e., a fraction) in simplest terms a/b, we define S(a/b) to be the sum of all positive
numbers of the form x/y where x is a positive divisor of a and y is a positive divisor of b. For example, the positive
divisors of 4 are 1, 2 and 4 and the positive divisors of 3 are 1 and 3, so S(4/3) = 1/1 + 2/1 + 4/1 + 1/3 + 2/3 + 4/3
= 28/3.
输入
Each line of input will be of the form a/b (with no white space) where a and b are integers in the range from 1 to 16000.
输出
Each line of output is of the form a/b where a and b are integers, and the fraction is in simplest terms (so 1/2 will
be output instead of 2/4 for example).
样例输入
6/1
2/3
100/49
样例输出
12/1
4/1
1767/7
求因子,分数相加
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef struct Fraction {//定义结构体变量,用于存储一个分数的分子和分母
int fenzi;
int fenmu;
} fraction;
fraction f[16001];//定义结构体变量数组
int gcd(int a,int b) {//求a和b的最大公约数
return b==0?a:gcd(b,a%b);
}
fraction addFraction(fraction f1,fraction f2) {//将两个结构体变量执行相加的操作(将两个分数相加)
fraction s;//使用s存储计算的结果,并作为返回值来进行返回。
if(f1.fenmu==f2.fenmu) {
s.fenzi=f1.fenzi+f2.fenzi;
s.fenmu=f1.fenmu;
} else {
s.fenmu=f1.fenmu*f2.fenmu;
s.fenzi=f1.fenzi*f2.fenmu+f2.fenzi*f1.fenmu;
}
int c=gcd(s.fenzi,s.fenmu);
s.fenzi = s.fenzi/c;
s.fenmu/=c;
return s;//分子和分母约分之后返回
}
int main() {
freopen("data.txt","r",stdin);
int a,b,snake1,snake2,whale1[16001],whale2[16001];
//whale是鲸鱼的意思(吃得多),这里可以表示存放因子的媒介,所以定义为数组
//whale1存放分子的因子,whale2存放分母的因子
while(scanf("%d/%d",&a,&b)!=EOF) {
snake1=0;//snake的英文单词是蛇的意思,snake1用于标记分子的各个因子
snake2=0;//snake的英文单词是蛇的意思,snake2用于标记分母的各个因子
for(int i=1; i<=a/2; i++) {//求分子的因子
if(a%i==0) {
whale1[snake1++] = i;
}
}
whale1[snake1++] =a;
for(int i=1; i<=b/2; i++) {//求分母的因子
if(b%i==0) {
whale2[snake2++] = i;
}
}
whale2[snake2++] =b;
fraction s;
s.fenmu=1,s.fenzi=0;
//将各个因子表示成的分数进行相加
for(int i=0; i<snake1; i++) {
for(int j=0; j<snake2; j++) {
fraction ff;
ff.fenzi=whale1[i];
ff.fenmu=whale2[j];
s = addFraction(s,ff);
}
}
printf("%d/%d\n",s.fenzi,s.fenmu);//输出结果
}
return 0;
}