比较两个部分(小于和朋友)两个、部分、朋友

2023-09-07 22:56:48 作者:゛乱了分寸的心动ぅ

我有两个部分我喜欢比较。它们存储这样的:

I have two fractions I like to compare. They are stored like this:

struct fraction {
    int64_t numerator;
    int64_t denominator;
};

目前,我对它们进行比较是这样的:

Currently, I compare them like this:

bool fraction_le(struct fraction a, struct fraction b)
{
    return a.numerator * b.denominator < b.numerator * a.denominator;
}

这工作得很好,除了(64位值)*(64位值)=(128位值),这意味着它会溢出的分子和分母的太远离零。

That works fine, except that (64 bit value) * (64 bit value) = (128 bit value), which means it will overflow for numerators and denominators that are too far away from zero.

我怎样才能作出比较总是工作,甚至荒唐的分数?

How can I make the comparison always works, even for absurd fractions?

喔,并顺便:馏分始终存储简化,并且仅分子可以是负的。也许这输入约束使一些算法可以...

Oh, and by the way: fractions are always stored simplified, and only the numerator can be negative. Maybe that input constraint makes some algorithm possible...

推荐答案

如果你正在使用gcc,你可以使用__int128。

If you are using GCC, you can use __int128.