题意:给定一个N,将0到1之间以1~N为分母的最简小数进行排序
解题思路:
- 读入N
- 用一个数组保存这一系列的最简小数,从1~N进行遍历,将相应的最简小数加入数组中。(如果分子分母的最大公因子为1,则为最简小数。最大公因子由辗转相除法得到)
- 使用快速排序将数组排序后输出即可
代码:
/*
ID: zc.rene1
LANG: C
PROG: frac1
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct fraction_number
{
int numerator;
int denominator;
};
struct fraction_number * array;
FILE *fout;
int IsSimple(int a, int b)
{
int common_factor = -1;
while (a*b != 0)
{
if (a > b)
{
a = a % b;
}
else
{
b = b % a;
}
}
common_factor = (a==0 ? b:a);
return common_factor==1 ? 1:0;
}
void PrintArray(int length)
{
int i;
for (i=0; i<length; i++)
{
fprintf(fout, "%d/%d\n", array[i].numerator, array[i].denominator);
}
}
int IsBigger(struct fraction_number a, struct fraction_number b)
{
if (a.numerator*b.denominator > a.denominator*b.numerator)
{
return 1;
}
return 0;
}
void Swap(struct fraction_number *a, struct fraction_number *b)
{
struct fraction_number temp;
temp = *a;
*a = *b;
*b = temp;
}
void QuickSort(int left, int right)
{
int key = (left + right)/2;
int i = left+1, j = right;
if (left >= right) return ;
Swap(&array[left], &array[key]);
while (1)
{
while (IsBigger(array[j], array[left]))
{
j--;
}
while (IsBigger(array[left], array[i]))
{
i++;
}
if (i<j)
{
Swap(&array[i], &array[j]);
}
else{
break;
}
if ((array[i].numerator==array[left].numerator)&&(array[i].denominator==array[left].numerator))
{
j--;
}
else
{
i++;
}
}
Swap(&array[j], &array[left]);
QuickSort(left, i-1);
QuickSort(j+1, right);
}
int main(void)
{
FILE *fin;
int N;
int i, j, index;
fin = fopen("frac1.in", "r");
fout = fopen("frac1.out", "w");
fscanf(fin, "%d", &N);
array = (struct fraction_number *)malloc((N+3)*N/2*sizeof(struct fraction_number));
memset(array, 0, (N+3)*N/2*sizeof(struct fraction_number));
struct fraction_number temp;
temp.numerator = 0;
temp.denominator = 1;
array[0] = temp;
temp.numerator = 1;
array[1] = temp;
index = 2;
for (i=1; i<=N; i++)
{
for (j=1; j<i; j++)
{
if (IsSimple(i, j))
{
struct fraction_number temp;
temp.numerator = j;
temp.denominator = i;
array[index++] = temp;
}
}
}
QuickSort(0, index-1);
PrintArray(index);
return 0;
}