首页 > 解决方案 > 周长为 n 的三角形

问题描述

我想打印有多少个三角形的周长为n。(整数边)。实际上我使用的公式是here。 T(n): n=偶数 --> n^2/48 | n=奇数 --> (n+3)^2/48。 这是我的代码:

        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            double m = 0;

            if(n%2==0)
            {
                m =Math.Round( n * n / 48.0);
            }
            else
            {
                m = Math.Round((n + 3) * (n + 3) / 48.0);
            }

            Console.Write(m);
        }

它实际上给了我一半的分数。

标签: c#

解决方案


原来问题是提问者应该处理n高达 1_000_000 的值。但是对于以整数乘法形式完成的此类输入n * n,会静默溢出并产生意外结果。

(奇怪的是,对于这些情况,它本来可以double更早地切换到,比如说n * (n / 48.0)or(double)n * n / 48.0而不是n * n / 48.0。)

您可以使用类似checked { /* statements here */}or 的语法(在表达式内部)checked(n * n)来获取异常,而不是固定宽度整数类型无法保存的有效位的静默丢失。

提问者通过切换到long

static void Main(string[] args)
{
    long n = long.Parse(Console.ReadLine());
    double m;

    if (n % 2 == 0)
    {
        m = Math.Round(n * n / 48.0);
    }
    else
    {
        m = Math.Round((n + 3) * (n + 3) / 48.0);
    }

    Console.Write(m);
}

如果您有权访问 System.Numerics,则可以编写一个适用于更大输入的解决方案:

static void Main(string[] args)
{
    BigInteger n = BigInteger.Parse(Console.ReadLine());
    BigInteger m;

    if (n % 2 == 0)
    {
        m = (n * n + 24) / 48;
    }
    else
    {
        m = ((n + 3) * (n + 3) + 24) / 48;
    }

    Console.Write(m);
}

我们使用整数除法/,并且将分母的一半添加到分子的技巧确保正确舍入到最接近的值。


推荐阅读