查找将n表示为两个带边界的整数之和的方式数量 [英] Find the number of ways to represent n as a sum of two integers with boundaries

查看:85
本文介绍了查找将n表示为两个带边界的整数之和的方式数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在打代码战,但是我真的被卡住了 解决以下有效问题.

I am playing around codefight, but I am really stuck to the following efficient issue.

问题:
在给定整数n,l和r的情况下,找到将n表示为两个整数A和B的总和的方式数,使得l≤A≤B≤r.

Problem:
Given integers n, l and r, find the number of ways to represent n as a sum of two integers A and B such that l ≤ A ≤ B ≤ r.

示例:
对于n = 6,l = 2和r = 4,输出应为 countSumOfTwoRepresentations2(n,l,r)= 2. 只有两种方法将6写入A + B,其中2≤A≤B≤4:6 = 2 + 4和6 = 3 + 3.

Example:
For n = 6, l = 2 and r = 4, the output should be countSumOfTwoRepresentations2(n, l, r) = 2. There are just two ways to write 6 as A + B, where 2 ≤ A ≤ B ≤ 4: 6 = 2 + 4 and 6 = 3 + 3.

这是我的代码.它通过了所有单元测试,但未通过 在隐藏的.有人可以以某种方式指导我吗? 预先感谢.

Here is my code. It passes all the unit tests but it failing in the hidden ones. Can someone direct me somehow? Thanks in advance.

public static int countSumOfTwoRepresentations2(int n, int l, int r) {
    int nrOfWays = 0;
    for(int i=l;i<=r;i++)
    {
        for(int j=i;j<=r;j++)
        {
            if(i+j==n)
                nrOfWays++;
        }
    }
    return nrOfWays;

}

推荐答案

好吧,不需要进行如此大的计算...它很容易计算:

Well, there's no need to make so huge calculations... It's easy to calculate:

public static int count(int n, int l, int r) {
    if (l > n/2)
        return 0;
    return Math.min(n/2 - l, r - n/2) + ((n%2 == 1) ? 0 : 1);
}

到目前为止,通过了我所有的测试.对于正面和负面也是如此.

Passes all my tests so far. For positives and negatives as well.

这篇关于查找将n表示为两个带边界的整数之和的方式数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆