27
\$\begingroup\$

Description

Subtract the next P numbers from a N number. The next number of N is N + 1.

Look at the examples to get what I mean.

Examples:

Input: N=2,P=3
Calculate: n - (n+1) - (n+2) - (n+3)     //Ending with 3, because P=3
Calculate: 2 -  2+1  -  2+2  - 2+3       //Replacing N with 2 from Input
Calculate: 2 -  3    -  4    - 5
Output: -10


Input: N=100,P=5
Calculate: n - (n+1) - (n+2) - (n+3) - (n+4) - (n+5)
Calculate: 100-  101 -  102  -  103  -  104  - 105
Output: -415


Input: N=42,P=0
Calculate: n
Calculate: 42
Output: 42


Input: N=0,P=3
Calculate: n - (n+1) - (n+2) - (n+3)
Calculate: 0 -  1    -  2    -  3
Output: -6


Input: N=0,P=0
Calulate: n
Calculate: 0
Output: 0

Input:

N: Integer, positive, negative or 0

P: Integer, positive or 0, not negative

Output:

Integer or String, leading 0 allowed, trailing newline allowed

Rules:

  • No loopholes
  • This is code-golf, so shortest code in bytes wins
  • Input and Output must be as described
\$\endgroup\$
  • 1
    \$\begingroup\$ The essential challenge here is calculating triangle numbers. \$\endgroup\$ – Peter Taylor Sep 1 '16 at 11:41
  • 4
    \$\begingroup\$ There's more to this than just triangular numbers; the start point is arbitrary as well as the number of subtractions, which may be zero. \$\endgroup\$ – JDL Sep 1 '16 at 11:45
  • \$\begingroup\$ Also, for triangular numbers it's possible that doing the actual sum is shorter than using the closed form, whereas you can't just compute arbitrary polygonal numbers by summing a range from 0 to N. (I'd agree with the close vote if the other challenge just asked for triangular numbers.) \$\endgroup\$ – Martin Ender Sep 1 '16 at 11:51
  • 1
    \$\begingroup\$ for the Input: N=0,P=3 example, your expansion has some extraneous double-negatives \$\endgroup\$ – turbulencetoo Sep 1 '16 at 14:36
  • 1
    \$\begingroup\$ @JDL, the part which is "more than just triangle numbers" is a simple multiplication: N * (P-1). That's virtually the definition of trivial. \$\endgroup\$ – Peter Taylor Sep 1 '16 at 15:12

35 Answers 35

15
\$\begingroup\$

05AB1E, 5 3 bytes

Saved 2 bytes thanks to Adnan

Ý+Æ

Explanation

Takes P then N as input.

       # implicit input, ex 5, 100
Ý      # range(0,X): [0,1,2,3,4,5]
 +     # add: [100,101,102,103,104,105]
  Æ    # reduced subtraction: 100-101-102-103-104-105
\$\endgroup\$
  • 4
    \$\begingroup\$ Ahhh, I almost wanted to post my solution haha. Also, for three bytes: Ý+Æ :). \$\endgroup\$ – Adnan Sep 1 '16 at 11:56
  • \$\begingroup\$ It only switches the input (P goes first) \$\endgroup\$ – Adnan Sep 1 '16 at 11:56
  • \$\begingroup\$ @Adnan: I didn't even know 05AB1E had Ý... I thought only 1-based range existed. \$\endgroup\$ – Emigna Sep 1 '16 at 11:58
  • \$\begingroup\$ In which character encoding is that only 3 Bytes? ;-) \$\endgroup\$ – yankee Sep 2 '16 at 14:14
  • 1
    \$\begingroup\$ @yankee: CP-1252 \$\endgroup\$ – Emigna Sep 2 '16 at 14:16
16
\$\begingroup\$

Python 2, 26 24 23 bytes

-2 bytes thanks to @Adnan (replace p*(p+1)/2 with p*-~p/2)
-1 byte thanks to @MartinEnder (replace -p*-~p/2 with +p*~p/2

lambda n,p:n-p*n+p*~p/2

Tests are on ideone

\$\endgroup\$
11
\$\begingroup\$

CJam, 8 bytes

{),f+:-}

Test suite.

Too bad that the closed form solution is longer. :|

Explanation

),  e# Get range [0 1 ... P].
f+  e# Add N to each value to get [N N+1 ... N+P].
:-  e# Fold subtraction over the list, computing N - (N+1) - (N+2) - ... - (N+P).
\$\endgroup\$
11
\$\begingroup\$

Haskell, 21 bytes

a#b=foldl1(-)[a..a+b]
\$\endgroup\$
10
\$\begingroup\$

Javascript (ES6), 20 19 18 bytes

n=>p=>n+p*(~p/2-n)

Saved 1 byte by currying, as suggested by Zwei
Saved 1 byte thanks to user81655

Test

let f =
n=>p=>n+p*(~p/2-n)

console.log(f(2)(3))
console.log(f(100)(5))
console.log(f(42)(0))
console.log(f(0)(3))
console.log(f(0)(0))

\$\endgroup\$
  • \$\begingroup\$ You can save a byte by currying the function. n=>p=>... and calling the function with f(n)(p) \$\endgroup\$ – Zwei Sep 1 '16 at 11:34
  • \$\begingroup\$ (n,p)=>n-p*(++p/2+n) will also works in C#. \$\endgroup\$ – aloisdg Sep 1 '16 at 11:36
  • 1
    \$\begingroup\$ n-p*(++p/2+n) is equivalent to n+p*(~p/2-n). \$\endgroup\$ – user81655 Sep 1 '16 at 14:38
8
\$\begingroup\$

Jelly, 4 bytes

r+_/

Try it online!

How it works

r+_/  Main link. Arguments: n, p

 +    Yield n+p.
r     Range; yield [n, ..., n+p].
  _/  Reduce by subtraction.
\$\endgroup\$
7
\$\begingroup\$

Haskell, 19 18 bytes

n#p=n+sum[-n-p..n]

Previous 19 bytes solutions

n#p=n-n*p-(p*p+p)/2
n#p=n-sum[n+1..n+p]
\$\endgroup\$
7
\$\begingroup\$

C#, 21 20 bytes

Edit: Saved one byte thanks to TheLethalCoder

N=>P=>N-P++*(N+P/2);

Try it online!

Full source, including test cases:

using System;

namespace substract
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>s=N=>P=>N-P++*(N+P/2);
            Console.WriteLine(s(2)(3));     //-10
            Console.WriteLine(s(100)(5));   //-415
            Console.WriteLine(s(42)(0));    //42
            Console.WriteLine(s(0)(3));     //-6
            Console.WriteLine(s(0)(0));     //0

        }
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ use currying N=>P=> instead of (N,P)=> to save 1 byte \$\endgroup\$ – TheLethalCoder Sep 2 '16 at 10:23
5
\$\begingroup\$

Mathematica, 15 bytes

#2-##-#(#+1)/2&

An unnamed function that receives P and n as its parameters in that order.

Uses the closed form solution n - n*p - p(p+1)/2.

\$\endgroup\$
5
\$\begingroup\$

Perl, 23 22 bytes

Includes +1 for -p

Give n and p (in that order) on separate lines of STDIN:

subtract.pl
2
3
^D

subtract.pl:

#!/usr/bin/perl -p
$_-=eval"+2+\$_++"x<>

(using '' quotes to save the \ invokes a 2 byte penalty because it can't be combined with -e)

Same idea and length:

#!/usr/bin/perl -p
$_+=eval"-1-++\$_"x<>

Surprisingly doing the actual calculation is shorter than using the direct formula (these $'s really hurt for arithmetic)

\$\endgroup\$
5
\$\begingroup\$

C++, 54 51 bytes

  [](int N,int P){int F=N;while(P--)F-=++N;return F;}

[](int N,int P){int F;for(F=N;P;F-=++N,P--);return F;}

Test:

#include <iostream>
int main(void)
{
    int N, P;
    std::cin >> N >> P;
    auto f = [](int N,int P){int F=N;while(P--)F-=++N;return F;};
    std::cout << f(N,P) << std::endl;
    return 0;
}
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to PPCG! Unfortunately, all submissions need to be programs or callable functions, whereas this is just a snippet that assumes the input to be stored in pre-defined variables and stores the output in another. \$\endgroup\$ – Martin Ender Sep 1 '16 at 12:06
  • 1
    \$\begingroup\$ @MartinEnder I have changed to C++ with lambda. Is it acceptable? \$\endgroup\$ – VolAnd Sep 1 '16 at 12:25
  • 1
    \$\begingroup\$ Yes, lambdas are fine. :) \$\endgroup\$ – Martin Ender Sep 1 '16 at 12:25
  • \$\begingroup\$ You can do this in C with 40 bytes f;g(n,p){f=n;while(p--)f-=++n;return f;} using your algorithm \$\endgroup\$ – cleblanc Sep 1 '16 at 13:35
  • \$\begingroup\$ @cleblanc Thanks for tip - global variable and declaration without an explicit type are really useful. What a pity that C99 standard removed implicit int \$\endgroup\$ – VolAnd Sep 2 '16 at 4:57
4
\$\begingroup\$

Pyke, 6 bytes

m+mhs-

Try it here!

m+     -    map(range(input_2), +input_1)
  mh   -   map(^, +1)
    s  -  sum(^)
     - - input_1 - ^
\$\endgroup\$
4
\$\begingroup\$

Brachylog, 19 17 bytes

hHyL,?+y:Lx+$_:H+

Explanation

hH                  Input = [H, whatever]
 HyL,               L = [0, …, H]
     ?+             Sum the two elements in the Input
       y            Yield the range from 0 to the result of the sum
        :Lx         Remove all elements of L from that range
           +        Sum the remaining elements
            $_      Negate the result
              :H+   Add H
\$\endgroup\$
4
\$\begingroup\$

MATL, 5 bytes

:y+s-

Inputs are P and then N.

Try it at MATL Online!

Explanation

:     % Take P implicitly. Range [1 2 ... P]
      %     Stack: [1 2 ... P]
y     % Take N implicitly at the bottom of the stack, and push another copy
      %     Stack: N, [1 2 ... P], N
+     % Add the top two arrays in the stack , element-wise
      %     Stack: N, [N+1 N+2 ... N+P]
s     % Sum of array
      %     Stack: N, N+1+N+2+...+N+P
-     % Subtract the top two numbers
      %     Stack: N-(N+1+N+2+...+N+P)
      % Implicitly display
\$\endgroup\$
3
\$\begingroup\$

Batch, 30 bytes

@cmd/cset/a%1-(%1*2+%2+1)*%2/2

Takes n and p as command-line parameters and prints the result without a trailing newline.

\$\endgroup\$
3
\$\begingroup\$

S.I.L.O.S, 80 bytes

GOTO b
lbla
n+1
m-n
i-1
GOTO d
lblb
readIO
n=i
m=n
readIO
lbld
if i a
printInt m

Try it online with test cases:
2,3
100,5
42,0
0,3
0,0

\$\endgroup\$
3
\$\begingroup\$

R, 17 14 bytes

N-N*P-sum(0:P)

Thanks to billywob for golfing away 3 bytes. Previous answer:

N-sum(N+if(P)1:P)

Note that 1:0 expands to the vector (1,0) so we need the if(P) condition (or to use seq_len, but that is more bytes). Without the condition, we would get the wrong output if P=0.

If P is zero, then the sum expands to sum(N+NULL), then to sum(numeric(0)), which is zero.

\$\endgroup\$
  • 3
    \$\begingroup\$ Not sure if this qualifies as a full program because it requires N and P to be already defined. Either way using n-n*p-sum(0:p) would be shorter anyways :) \$\endgroup\$ – Billywob Sep 1 '16 at 11:50
  • \$\begingroup\$ My interpretation of the problem is that N and P are already defined (other answers seem to take this line as well). Golfing point taken though. \$\endgroup\$ – JDL Sep 1 '16 at 12:19
  • 3
    \$\begingroup\$ Unless specified otherwise submissions need to be full programs or callable functions not just snippets. Which other answers make the assumption that the variables are already defined? \$\endgroup\$ – Martin Ender Sep 1 '16 at 12:30
  • \$\begingroup\$ I'm not a javascript expert, but it looks like the javascript solution is taking the variables as already defined. That could be my own misunderstanding though. Since N and P were named as such in the problem, I took that as "specified otherwise". If not, then we need a wrapper function(N,P){...} or N=scan();P=scan();... \$\endgroup\$ – JDL Sep 1 '16 at 12:47
  • \$\begingroup\$ @JDL the javascript entry doesn't take predefined variabled \$\endgroup\$ – Blue Sep 1 '16 at 14:08
3
\$\begingroup\$

PHP, 33 Bytes

$n-=$n*$p+array_sum(range(0,$p));
\$\endgroup\$
  • \$\begingroup\$ I think you need to use <?php or short <? for PHP-Code. Please edit your answer. \$\endgroup\$ – Paul Schmitz Sep 1 '16 at 16:16
  • \$\begingroup\$ php.net/manual/de/features.commandline.usage.php not from the command line \$\endgroup\$ – Jörg Hülsermann Sep 1 '16 at 17:40
  • \$\begingroup\$ Sorry, forget what said. I have seen many answers with this, and therefore thought, that there is a rule for that, which is not the case. There should be one, to avoid discussions like this one. \$\endgroup\$ – Paul Schmitz Sep 1 '16 at 18:00
3
\$\begingroup\$

Jelly, 7 bytes

RS+×_×-

Arguments are P, N
Test it on TryItOnline

How?

RS+×_×-  - takes two arguments: P, N
R        - range(P): [1,2,3, ... ,P]
 S       - sum: 1+2+3+ ... +P
   ×     - multiply: P*N
  +      - add: 1+2+3+ ... +P + P*N
    _    - subtract: 1+2+3+ ... +P + P*N - N
      -  - -1
     ×   - multiply: (1+2+3+ ... +P + P*N - N)*-1
                   = -1-2-3- ... -P - P*N + N
                   = N - (N+1) - (N+2) - (N+3) - ... - (N+P)
\$\endgroup\$
3
\$\begingroup\$

Pyth - 6 bytes

-F}Q+E

Test Suite.

\$\endgroup\$
3
\$\begingroup\$

Java, 67, 63 bytes

Golfed:

int x(int n,int p){return-((p%2<1)?p*p/2+p:p/2*(p+2)+1)+n-p*n;}

Ungolfed:

int x(int n, int p)
{
    return -((p%2<1) ? p*p/2+p : p/2 * (p+2) + 1) + n - p*n;
}

Basically I did some math on the formula. The n - p*n part takes care of the all n's in the formula. Then I used a super fun property of summing together linearly increasing set of integers (arithmetic series): I used the sum of first and last integer and then multiply it by set.length / 2 (I also check for the parity and handle it appropriately).

Try it: https://ideone.com/DEd85A

\$\endgroup\$
  • \$\begingroup\$ You can remove the space between int n,int p to save a byte. Also, you can change the p%2==0 to p%2<1 to save another byte. -- I wasn't aware you had already posted a Java answer when I posted my shorter variant with for-loop. I like your mathematical formula, though, so +1 from me. :) \$\endgroup\$ – Kevin Cruijssen Sep 1 '16 at 13:40
  • \$\begingroup\$ Great formula! Using p%2>0 and switching the order in the ternary you can save a character. \$\endgroup\$ – Frozn Sep 1 '16 at 18:40
  • \$\begingroup\$ Oh and also p/2 *(p+2) is equal to p*p/2+p \$\endgroup\$ – Frozn Sep 1 '16 at 18:48
  • \$\begingroup\$ Hehe great improvements :) actually this formula comes from a funny anecdote :) @KevinCruijssen nice answer, definitely better than mine :) +1 \$\endgroup\$ – peech Sep 2 '16 at 9:16
3
\$\begingroup\$

Java 7, 43 40 bytes

int c(int n,int p){return n-p*n+p*~p/2;}

Java 8, 19 bytes

(n,p)->n-p*n+p*~p/2

Shamelessly stolen from @JonathanAllan's amazing Python 2 formula.

Original answer (61 60 bytes):

int c(int n,int p){int r=n,i=1;for(;i<p;r-=n+++i);return r;}

Ungolfed & test cases:

Try it here.

class M{
  static int c(int n, int p){
    return n - p*n + p*~p / 2;
  }

  public static void main(String[] a){
    System.out.println(c(2, 3));
    System.out.println(c(100, 5));
    System.out.println(c(42, 0));
    System.out.println(c(0, 3));
    System.out.println(c(0, 0));
  }
}

Output:

-10
-415
42
-6
0
\$\endgroup\$
  • \$\begingroup\$ What about this requires Java 7? \$\endgroup\$ – mbomb007 Sep 2 '16 at 13:15
  • \$\begingroup\$ @mbomb007 int c(int n,int p){...}. If it would have been Java 8 (or 9) it could have been (n,p)->n-p*n+p*~p/2 (19 bytes) \$\endgroup\$ – Kevin Cruijssen Sep 2 '16 at 13:16
  • \$\begingroup\$ Then do that to save those bytes. \$\endgroup\$ – mbomb007 Sep 2 '16 at 13:19
3
\$\begingroup\$

Fourier, 34 bytes

I~No~OI~P>0{1}{@P+N(N^~NO-N~ON)Oo}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Labyrinth, 15 bytes

?:?:}*-{:)*#/-!

or

??:}`)*{:)*#/-!

Uses the closed form solution n - n*P - P*(P+1)/2.

\$\endgroup\$
2
\$\begingroup\$

php, 38 bytes

<?=$argv[1]*(1-$a=$argv[2])-$a++*$a/2;
\$\endgroup\$
2
\$\begingroup\$

Forth, 36 bytes

Simple computation of n - (p*n + (p^2+p) / 2)

: f 2dup dup dup * + 2/ -rot * + - ;

Try it online

\$\endgroup\$
1
\$\begingroup\$

Pyth, 11 bytes

Ms+Gm_+GdSH

A function g that takes input of n and p via argument and prints the result. It can be called in the form gn p.

Try it online

How it works

Ms+Gm_+GdSH  Function g. Inputs: G, H
M            g=lambda G,H:
         SH   1-indexed range, yielding [1, 2, 3, ..., H]
    m_+Gd     Map lambda d:-(G+d) over the above, yielding [-(G+1), -(G+2), -(G+3),
              ..., -(G+H)]
  +G          Add G to the above, yielding [G, -(G+1), -(G+2), -(G+3), ..., -(G+H)]
 s            Reduce on addition with base case 0, yielding G-(G+1)-(G+2)-(G+3)...
              -(G+H)
              Implicitly print
\$\endgroup\$
1
\$\begingroup\$

C89, 38, 35, 33 bytes

h(n,p,r)int*r;{*r=n-p++*(n+p/2);}

Test it on Coliru.

\$\endgroup\$
1
\$\begingroup\$

Maple, 19 bytes

n-sum(i,i=n+1..n+p)

Usage:

> f:=(n,p)->n-sum(i,i=n+1..n+p);
> f(2, 3);
  -10
> f(100,5);
  -415
> f(42,0);
  42
\$\endgroup\$
1
\$\begingroup\$

Perl 6, 21 bytes

{$^n-[+] $n^..$n+$^p}

Explanation:

# bare block lambda with two placeholder parameters 「$n」 and 「$p」
{
  $^n -
      # reduce using 「&infix:<+>」
      [+]
          # a Range that excludes 「$n」 and has 「$p」 values after it
          $n ^.. ($n + $^p)
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.