Representing fraction in decimal form where recurring is placed in brackets

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


//Struct to store remainders and their result starting position
typedef struct
{
int rem;
int pos;
}Rem;


char * Div(int a, int b)
{

//Buffer to store the result maximum of 127 digits
char *result = malloc(sizeof(int) * 128);

//Array to store remainders
Rem rems[128];
int m = 0;

//Variable to store the next free location in buffer
int n = sprintf(result, "%d", a/b);

//Variable to store the current remainder
int rem = a % b;

//Checkng whether a is multiple of b
if(!rem)
return result;

//Adding decimal
result[n++] = '.';

//loop variable
int i;
while(1)
{
//store the remainder in array
rems[m].pos = n;
rems[m++].rem = rem;

//multiply remainder with 10
//
while(rem < b)
{
rem *= 10;
if(rem < b) //still less than b
{
result[n++] = '0'; //Add zero to the result
rem *= 10;
}
}

//store the dividend
n += snprintf(result + n, 127 - n, "%d", rem/b);

//if buffer full return
if(n == 127)
{
result[n] = '';
return result;
}

rem %= b;

//if remainder zero return
if(!rem)
return result;

for(i = 0; i < m && rems[i].rem != rem ; ++i) //linear search of current remainder in rems array
{
}

if(i != m) //if found, it is repeating
{
memmove(result + rems[i].pos + 1, result + rems[i].pos, n - rems[i].pos);
result[rems[i].pos] = '(';
result[n+1] = ')';
result[n+2] = '';

return result;
}
}
}

int main()
{
int m, n ;
scanf("%d %d", &m, &n);
char *res = Div(m,n);

printf("%s\n", res);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s