Subtract the next numbers

27

1

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

Paul Schmitz

Posted 2016-09-01T11:02:33.810

Reputation: 1 089

1The essential challenge here is calculating triangle numbers. – Peter Taylor – 2016-09-01T11:41:27.687

4There's more to this than just triangular numbers; the start point is arbitrary as well as the number of subtractions, which may be zero. – JDL – 2016-09-01T11:45:41.440

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.) – Martin Ender – 2016-09-01T11:51:01.323

1for the Input: N=0,P=3 example, your expansion has some extraneous double-negatives – turbulencetoo – 2016-09-01T14:36:21.100

1@JDL, the part which is "more than just triangle numbers" is a simple multiplication: N * (P-1). That's virtually the definition of trivial. – Peter Taylor – 2016-09-01T15:12:56.523

why are there double minuses for N=0,P=3? Typo, right? – Tasos Papastylianou – 2016-09-02T09:52:57.540

@MartinEnder, someone on meta found an even closer duplicate.

– Peter Taylor – 2016-09-05T13:39:18.783

Answers

15

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

Emigna

Posted 2016-09-01T11:02:33.810

Reputation: 50 798

4Ahhh, I almost wanted to post my solution haha. Also, for three bytes: Ý+Æ :). – Adnan – 2016-09-01T11:56:33.863

It only switches the input (P goes first) – Adnan – 2016-09-01T11:56:58.623

@Adnan: I didn't even know 05AB1E had Ý... I thought only 1-based range existed. – Emigna – 2016-09-01T11:58:33.460

In which character encoding is that only 3 Bytes? ;-) – yankee – 2016-09-02T14:14:49.583

1@yankee: CP-1252 – Emigna – 2016-09-02T14:16:41.913

16

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

Jonathan Allan

Posted 2016-09-01T11:02:33.810

Reputation: 67 804

11

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).

Martin Ender

Posted 2016-09-01T11:02:33.810

Reputation: 184 808

11

Haskell, 21 bytes

a#b=foldl1(-)[a..a+b]

ThreeFx

Posted 2016-09-01T11:02:33.810

Reputation: 1 435

10

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))

Arnauld

Posted 2016-09-01T11:02:33.810

Reputation: 111 334

You can save a byte by currying the function. n=>p=>... and calling the function with f(n)(p) – Zwei – 2016-09-01T11:34:17.157

(n,p)=>n-p*(++p/2+n) will also works in C#. – aloisdg moving to codidact.com – 2016-09-01T11:36:52.463

1n-p*(++p/2+n) is equivalent to n+p*(~p/2-n). – user81655 – 2016-09-01T14:38:55.730

8

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]

Damien

Posted 2016-09-01T11:02:33.810

Reputation: 2 407

8

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.

Dennis

Posted 2016-09-01T11:02:33.810

Reputation: 196 637

7

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

        }
    }
}

adrianmp

Posted 2016-09-01T11:02:33.810

Reputation: 1 592

1use currying N=>P=> instead of (N,P)=> to save 1 byte – TheLethalCoder – 2016-09-02T10:23:02.477

5

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)

Ton Hospel

Posted 2016-09-01T11:02:33.810

Reputation: 14 114

5

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;
}

VolAnd

Posted 2016-09-01T11:02:33.810

Reputation: 296

2

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.

– Martin Ender – 2016-09-01T12:06:45.170

1@MartinEnder I have changed to C++ with lambda. Is it acceptable? – VolAnd – 2016-09-01T12:25:24.090

1

Yes, lambdas are fine. :)

– Martin Ender – 2016-09-01T12:25:59.343

You can do this in C with 40 bytes f;g(n,p){f=n;while(p--)f-=++n;return f;} using your algorithm – cleblanc – 2016-09-01T13:35:32.230

@cleblanc Thanks for tip - global variable and declaration without an explicit type are really useful. What a pity that C99 standard removed implicit int – VolAnd – 2016-09-02T04:57:15.103

5

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.

Martin Ender

Posted 2016-09-01T11:02:33.810

Reputation: 184 808

4

Pyke, 6 bytes

m+mhs-

Try it here!

m+     -    map(range(input_2), +input_1)
  mh   -   map(^, +1)
    s  -  sum(^)
     - - input_1 - ^

Blue

Posted 2016-09-01T11:02:33.810

Reputation: 26 661

4

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

Fatalize

Posted 2016-09-01T11:02:33.810

Reputation: 32 976

4

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

Luis Mendo

Posted 2016-09-01T11:02:33.810

Reputation: 87 464

4

Forth, 36 bytes

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

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

Try it online

mbomb007

Posted 2016-09-01T11:02:33.810

Reputation: 21 944

3

Fourier, 34 bytes

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

Try it online!

Beta Decay

Posted 2016-09-01T11:02:33.810

Reputation: 21 478

3

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.

Neil

Posted 2016-09-01T11:02:33.810

Reputation: 95 035

3

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

betseg

Posted 2016-09-01T11:02:33.810

Reputation: 8 493

3

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.

JDL

Posted 2016-09-01T11:02:33.810

Reputation: 1 135

3Not 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 :) – Billywob – 2016-09-01T11:50:10.743

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. – JDL – 2016-09-01T12:19:56.027

3

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?

– Martin Ender – 2016-09-01T12:30:39.553

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();... – JDL – 2016-09-01T12:47:31.077

@JDL the javascript entry doesn't take predefined variabled – Blue – 2016-09-01T14:08:37.090

does an R expression qualify as a "function-like construct"? Note that in R, an expression is its own class, can be evaluated directly, and is distinct from a snippet. – JDL – 2016-09-02T12:39:15.717

taking the variables as already defined, javascript would be 12 bytes n+p*(~p/2-n) – edc65 – 2016-09-02T18:26:48.380

3

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

peech

Posted 2016-09-01T11:02:33.810

Reputation: 309

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. :)

– Kevin Cruijssen – 2016-09-01T13:40:29.727

Great formula! Using p%2>0 and switching the order in the ternary you can save a character. – Frozn – 2016-09-01T18:40:09.837

Oh and also p/2 *(p+2) is equal to p*p/2+p – Frozn – 2016-09-01T18:48:59.127

Hehe great improvements :) actually this formula comes from a funny anecdote :) @KevinCruijssen nice answer, definitely better than mine :) +1

– peech – 2016-09-02T09:16:18.763

3

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

Kevin Cruijssen

Posted 2016-09-01T11:02:33.810

Reputation: 67 575

What about this requires Java 7? – mbomb007 – 2016-09-02T13:15:16.343

@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) – Kevin Cruijssen – 2016-09-02T13:16:58.903

Then do that to save those bytes. – mbomb007 – 2016-09-02T13:19:18.250

3

PHP, 33 Bytes

$n-=$n*$p+array_sum(range(0,$p));

Jörg Hülsermann

Posted 2016-09-01T11:02:33.810

Reputation: 13 026

I think you need to use <?php or short <? for PHP-Code. Please edit your answer. – Paul Schmitz – 2016-09-01T16:16:32.773

http://php.net/manual/de/features.commandline.usage.php not from the command line – Jörg Hülsermann – 2016-09-01T17:40:49.610

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. – Paul Schmitz – 2016-09-01T18:00:46.483

3

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)

Jonathan Allan

Posted 2016-09-01T11:02:33.810

Reputation: 67 804

3

Pyth - 6 bytes

-F}Q+E

Test Suite.

Maltysen

Posted 2016-09-01T11:02:33.810

Reputation: 25 023

2

Burlesque, 12 bytes

perz?+{.-}r[

Try it online!

pe     #Read input as P, N
rz     #Range (0,N)
?+     #Add P to each
{.-}r[ #Reduce via subtraction

DeathIncarnate

Posted 2016-09-01T11:02:33.810

Reputation: 916

2

Labyrinth, 15 bytes

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

or

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

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

Martin Ender

Posted 2016-09-01T11:02:33.810

Reputation: 184 808

2

php, 38 bytes

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

user59178

Posted 2016-09-01T11:02:33.810

Reputation: 1 007

1

Excel, 20 bytes

Subtract the next B1 integers from A1:

=A1-B1*(A1+(B1+1)/2)

Wernisch

Posted 2016-09-01T11:02:33.810

Reputation: 2 534

1

GolfScript, 11 bytes

Formula stolen elsewhere...

~1$1$)2/+*-

Try it online!

Explanation

This just boils down to

A-B*(A+(B+1)/2)

Converted to postfix.

GolfScript, 15 bytes

~),{1$+}%{-}*\;

Try it online!

Explanation

~               # Evaluate the input
 ),             # Generate inclusive range
   {1$+}%       # Add each item by the other input
         {-}*   # Reduce by difference
             \; # Discard the extra other input

user85052

Posted 2016-09-01T11:02:33.810

Reputation:

1

Keg, -hr, 8 6 bytes

+ɧ^∑$-

Try it online!

No formula, just a for loop!

Lyxal

Posted 2016-09-01T11:02:33.810

Reputation: 5 253

1

W d, 6 4 bytes

Surprised to see that it's not short at all. (Although it at least ties with Jelly...)

7▄i←

Explanation

Uncompressed:

+.@-R
+     % Generate b+a
 .    % Generate range(a,b+a)
  @-R % Reduce via subtraction

user85052

Posted 2016-09-01T11:02:33.810

Reputation:

1

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

TheBikingViking

Posted 2016-09-01T11:02:33.810

Reputation: 3 674

1

C89, 38, 35, 33 bytes

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

Test it on Coliru.

YSC

Posted 2016-09-01T11:02:33.810

Reputation: 732

1

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

DSkoog

Posted 2016-09-01T11:02:33.810

Reputation: 560

1

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)
}

Brad Gilbert b2gills

Posted 2016-09-01T11:02:33.810

Reputation: 12 713

1

Java 8, 25 bytes

(n,p)->n-(p*n+p*(p+1)/2);

Ungolfed test program

public static void main(String[] args) {

    BiFunction<Integer, Integer, Integer> f = (n, p) -> n - (p * n + p * (p + 1) / 2);
    System.out.println(f.apply(100, 5));
}

Shaun Wild

Posted 2016-09-01T11:02:33.810

Reputation: 2 329

1

Scala, 41 bytes

def?(n:Int,p:Int)=n-(1 to p).map{n+_}.sum

Testing code:

println(?(2,3))
println(?(100,5))
println(?(42,0))
println(?(0,3))
println(?(0,0))

// Output
-10
-415
42
-6
0

AmazingDreams

Posted 2016-09-01T11:02:33.810

Reputation: 281

1

Clojure/Clojurescript, 30 bytes

#(reduce -(range %(+ 1 % %2)))

The straightforward approach is shorter than the mathematically clever ones.

MattPutnam

Posted 2016-09-01T11:02:33.810

Reputation: 521

1

Julia: 17-18 bytes (13 as program with terminal inputs)

As per suggestion in comments that "function or program" form is needed:

  • as function: 17 characters, 18 bytes if you count ∘ as multibyte

    n∘r=2n-sum(n:n+r)  
    

    usage: 5∘3 outputs -16

  • as program, passed initial parameters from terminal: 13 bytes:

    2n-sum(n:n+r)  
    

    usage: julia -E 'n,r=5,3;include("codegolf.jl")'

Tasos Papastylianou

Posted 2016-09-01T11:02:33.810

Reputation: 233

1

Nice solution, but all submissions need to be callable functions or full programs not just snippets. I think the shortest fix would be to define it as a binary operator by prepending n\r=.

– Martin Ender – 2016-09-03T09:04:44.107

Thanks, I edited to that effect. \ is a bad choice because it needs to be explicitly imported, although I suppose this is the kind of thing that could fall under a gray area. (but if I were allowed to do that, I might as well say Σ(n:n+r) where Σ is an alias for sum :p ). An "initialise and call" from the terminal feels like a bit of a cheat, but again it's a gray area, since other submissions do this without problem since it's considered the only way to call the program. – Tasos Papastylianou – 2016-09-03T13:16:00.947