Find the number of ways to represent n as a sum of two integers with boundaries

北战南征 提交于 2019-12-11 00:56:03

问题


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

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.

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;

}

回答1:


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.




回答2:


In java:

int countSumOfTwoRepresentations2(int n, int l, int r)
{
     return Math.max(0,Math.min(n/2-l,r-n/2)+(n+1)%2);
}

In Python3:

def countSumOfTwoRepresentations2(n, l, r):
    return max(0,min(n//2-l,r-n//2)+(n+1)%2)



回答3:


int countSumOfTwoRepresentations(int n, int l, int r)
  {
    int r1 = 0;
    if (n > l + r || n < 2 * l)
        return 0;
    r1 = n - l;
    if ((r1 - l) % 2 == 0)
        return (r1 - l) / 2 + 1;
    else
        return (r1 - l + 1) / 2;
}


来源:https://stackoverflow.com/questions/39860021/find-the-number-of-ways-to-represent-n-as-a-sum-of-two-integers-with-boundaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!