Is my friend cheating?

coderwars Is my friend cheating?

  • A friend of mine takes the sequence of all numbers from 1 to n (where n > 0).
  • Within that sequence, he chooses two numbers, a and b
  • He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
  • Given a number n, could you tell me the numbers he excluded from the sequence?
    The function takes the parameter: n (n is always strictly greater than 0) and returns an array or a string (depending on the language) of the form:
[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or or [{a, b}, ...]

with all (a, b) which are the possible removed numbers in the sequence 1 to n.
[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or ...will be sorted in increasing order of the “a”.
It happens that there are several possible (a, b). The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth! (Go: in this case return nil).
Examples:

removNb(26) should return [(15, 21), (21, 15)]
or
removNb(26) should return { {15, 21}, {21, 15} }
or
removeNb(26) should return [[15, 21], [21, 15]]
or
removNb(26) should return [ {15, 21}, {21, 15} ]
or
removNb(26) should return "15 21, 21 15"

or

in C:
removNb(26) should return  {{15, 21}{21, 15}} tested by way of strings.
Function removNb should return a pointer to an allocated array of Pair pointers, each one also allocated. 
/*
   We desire: ab = 1 + ... + n - a - b
   Take advantage of b = sum - a
                         -------
                          a + 1
   */
   public static List<long[]> removNb(long n) {
       List<long[]> res = new ArrayList<long[]>();
       long sum = (1 + n) * n >>> 1;
       for (long a = 1; a <= n; a++) {
           long b = (sum - a) / (a + 1);
           if (b <= n && b * (a + 1) == (sum - a)) {
               res.add(new long[] { a, b });
           }
       }
       return res;
   }
  // 写法二
  public static List<long[]> removNb(long n) {
       long sum = (1 + n) * n >>> 1;
       return LongStream.rangeClosed(1, n).filter(a -> (sum - a) % (a + 1) == 0)
               .mapToObj(a -> new long[] { a, (sum - a) / (a + 1) }).filter(arr -> arr[1] <= n)
               .collect(Collectors.toList());
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值