-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFraction.c
117 lines (112 loc) · 1.99 KB
/
Fraction.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
struct Fraction
{
long long int num;
long long int den;
};
struct Fraction new_Fraction(long long int num,long long int den)
{
struct Fraction ans;
ans.num=num;
ans.den=den;
return ans;
}
long long int gcd(long long a,long long b)
{
a=abs(a);
b=abs(b);
if(a>b)
{
int temp=a;
a=b;
b=temp;
}
if(a==0)
return b;
else
return gcd(b%a,a);
}
struct Fraction reduce_Fraction(struct Fraction a)
{
long long g=gcd(a.num,a.den);
struct Fraction ans;
ans.num=a.num/g;
ans.den=a.den/g;
return ans;
}
struct Fraction add_Fraction(struct Fraction a,struct Fraction b)
{
long long int x=a.num * b.den + b.num * a.den;
long long int y=a.den * b.den;
return reduce_Fraction(new_Fraction(x,y));
}
struct Fraction subtract_Fraction(struct Fraction a,struct Fraction b)
{
long long int x=a.num * b.den - b.num * a.den;
long long int y=a.den * b.den;
return reduce_Fraction(new_Fraction(x,y));
}
char* num_to_string(int x)
{
int nflag=0;
if(x<0)
{
x=-x;
nflag=1;
}
int j=0;
int temp[10];
while(x>0)
{
temp[j]=x%10+'0';
x=x/10;
j++;
}
int n=j;
char* ans=(char*)malloc(sizeof(char)*20);
int p=0;
if(nflag==1)
{
ans[p]='-';
p++;
}
j--;
while(j>=0)
{
ans[p]=temp[j];
p++;
j--;
}
if(p==0)
{
ans[p]='0';
p++;
}
ans[p]='\0';
return ans;
}
void concatinate(char* target,char* str)
{
int j=0;
while(target[j]!='\0')
j++;
int k=0;
while(str[k]!='\0')
{
target[j]=str[k];
k++;
j++;
}
target[j]='\0';
}
char* Fraction_to_string(struct Fraction a)
{
char* ans=(char*)malloc(sizeof(char)*20);
ans[0]='\0';
char* ax=num_to_string(a.num);
char* b="/";
char* c=num_to_string(a.den);
concatinate(ans,ax);
concatinate(ans,b);
concatinate(ans,c);
return ans;
}