Product over a range

40

2

Your task is simple: given two integers a and b, output ∏[a,b]; that is, the product of the range between a and b. You may take a and b in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. a will always be less than b.

Note that the end may be exclusive or inclusive of b. I'm not picky. ^_^

Test cases

[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24

This is a , so the shortest program in bytes wins.


Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the snippet:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=66202,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

Conor O'Brien

Posted 2015-12-10T02:46:26.057

Reputation: 36 228

2I'm answering this in TI-BASIC tomorrow. – SuperJedi224 – 2015-12-10T02:48:28.700

@SuperJedi224 Good luck ;) – Conor O'Brien – 2015-12-10T02:48:56.463

Can the input be taken as b, a? – FlipTack – 2017-02-12T20:01:02.423

@FlipTack yes you can – Conor O'Brien – 2017-02-12T20:03:07.273

Answers

37

Jelly, 2 bytes

rP

Takes two numbers as command line arguments. Try it online.

Note that this is inclusive range. For the cost of a byte (3 bytes), we can make this exclusive:

’rP

Try it online. Note that the arguments must be given in the order b a for this version.

Explanation

Inclusive

a rP b
  r   dyadic atom, creates inclusive range between a and b
   P  computes product of the list

Exclusive

b ’rP a
  ’   decrement b (by default, monadic atoms in dyadic chains operate on the left argument)
   r  range
    P product 

a spaghetto

Posted 2015-12-10T02:46:26.057

Reputation: 10 647

11I doubt this is beatable... – kirbyfan64sos – 2015-12-10T02:52:50.343

17@kirbyfan64sos you jelly? – Aaron – 2015-12-10T13:23:23.577

31

ArnoldC, 522 511 bytes

First post on codegolf !

I had fun doing this. Exclusive range.

LISTEN TO ME VERY CAREFULLY f
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE r
YOU SET US UP 1
HEY CHRISTMAS TREE l
YOU SET US UP 1
STICK AROUND l
GET TO THE CHOPPER r
HERE IS MY INVITATION r
YOU'RE FIRED a
ENOUGH TALK
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP 1
ENOUGH TALK
GET TO THE CHOPPER l
HERE IS MY INVITATION b
LET OFF SOME STEAM BENNET a
ENOUGH TALK
CHILL
I'LL BE BACK r
HASTA LA VISTA, BABY

Explanations (Thanks Bijan):

DeclareMethod f
        MethodArguments a
        MethodArguments b
        NonVoidMethod
        DeclareInt r
        SetInitialValue 1
        DeclareInt l
        SetInitialValue 1
        WHILE l
                AssignVariable r
                        SetValue r
                        MultiplicationOperator a
                EndAssignVariable
                AssignVariable a
                        SetValue a
                        + 1
                EndAssignVariable
                AssignVariable l
                        SetValue b
                        > a
                EndAssignVariable
        EndWhile
        Return r
EndMethodDeclaration

Zycho

Posted 2015-12-10T02:46:26.057

Reputation: 441

Hahaha... I am stil laughing – rpax – 2015-12-10T20:23:38.790

but an explanation would be great – rpax – 2015-12-10T20:25:40.717

Here it is converted and indented using this as reference – Bijan – 2015-12-10T23:22:53.570

Which interpreter are you using? – lirtosiast – 2015-12-10T23:58:23.053

The official one. You're right about @NO PROBLEMO and 1 (not 0 ;) )

– Zycho – 2015-12-11T09:12:58.360

the wierdest language i ever came across honestly ! – Abr001am – 2015-12-11T09:21:25.073

This isn't weird, this is Arnold ! Take a look at the official page or the wiki if you like it

– Zycho – 2015-12-11T15:13:48.473

Get up. Enough talk. Get to the chopper. – m654 – 2016-06-08T15:43:24.043

19

Python, 30 bytes

f=lambda a,b:a>b or a*f(a+1,b)

Inclusive range. Repeatedly multiplies by and increments the left endpoint, until it is higher than the right endpoint, in which case it's the empty product of 1 (as True).

xnor

Posted 2015-12-10T02:46:26.057

Reputation: 115 687

15

Minecraft 15w35a+, program size 456 total (see below)

enter image description here

This calculates PI [a,b). Input is given by using these two commands: /scoreboard players set A A {num} and /scoreboard players set B A {num}. Remember to use /scoreboard objectives add A dummy before input.

Scored using: {program size} + ( 2 * {input command} ) + {scoreboard command} = 356 + ( 2 * 33 ) + 34 = 456.

This code corresponds to the following psuedocode:

R = 1
loop:
  R *= A
  A += 1
  if A == B:
    print R
    end program

Download the world here.

GamrCorps

Posted 2015-12-10T02:46:26.057

Reputation: 7 058

Program size is counted by this scoring method.

– GamrCorps – 2015-12-10T23:47:58.670

Dammit, you got to it before I did. :I – Addison Crump – 2015-12-11T11:25:00.507

You need to specify snapshot version, i.e. 15w46a or something. – Addison Crump – 2015-12-11T11:26:45.857

1Minecraft :D LoL, golfing in Minecraft :D – username.ak – 2016-02-03T10:07:36.277

13

Python 2, 44 38 bytes

lambda l:reduce(int.__mul__,range(*l))

Pretty much the obvious anonymous function answer.

EDIT: Thanks to xnor for saving 6 bytes with some features I didn't know.

quintopia

Posted 2015-12-10T02:46:26.057

Reputation: 3 899

1You can use the built-in int.__mul__, which works in place of your lambda. The two numbers x,y can also be written unpacked as *l. – xnor – 2015-12-10T03:32:42.473

37Crossed out 44 still looks like 44. – a spaghetto – 2015-12-10T03:45:35.727

12

TI-BASIC, 9 bytes

Input A
prod(randIntNoRep(A,Ans

Takes one number from Ans and another from a prompt.

Also 9 bytes, taking input as a list from Ans:

prod(randIntNoRep(min(Ans),max(Ans

lirtosiast

Posted 2015-12-10T02:46:26.057

Reputation: 20 331

1It took me a while to figure out for myself, so I'm gonna post it here: Each function in TI-BASIC is one byte. – Fund Monica's Lawsuit – 2015-12-11T20:13:11.703

3@QPaysTaxes Lots of them do, but not all of them. % is two bytes. – mbomb007 – 2015-12-11T21:20:43.480

10

Pyth, 5 bytes

*FrQE

Pyth doesn't have product, so we reduce * over the range.

Uses exclusive range.

lirtosiast

Posted 2015-12-10T02:46:26.057

Reputation: 20 331

4*FrFQ is equivalent but with different input, just for fun :) – FryAmTheEggman – 2015-12-10T03:24:09.230

10

R, 22 bytes

function(a,b)prod(a:b)

freekvd

Posted 2015-12-10T02:46:26.057

Reputation: 909

8

Mathematica, 15 bytes

1##&@@Range@##&

A shorter solution that only works for non-negative integers:

#2!/(#-1)!&

alephalpha

Posted 2015-12-10T02:46:26.057

Reputation: 23 988

3Even shorter for non-negative integers: #2!#/#!& – Anders Kaseorg – 2016-03-25T22:52:56.937

8

JavaScript (ES6), 34 bytes

(a,b)=>eval("for(c=a;a<b;)c*=++a")

Sometimes the simplest answer is the best! Just a for loop inside eval. Inclusive range.

user81655

Posted 2015-12-10T02:46:26.057

Reputation: 10 181

Wow. That's impressive! – Conor O'Brien – 2015-12-10T12:13:53.620

Aw man, I thought of this exact solution while trying to golf mine just now... +1 – ETHproductions – 2015-12-10T16:04:35.583

1This one is even shorter with 25 characters:

f=(a,b)=>a<b?a*f(a+1,b):1 – Matthias Burtscher – 2019-05-14T18:26:11.357

7

Japt, 7 bytes

Easy challenges like this are always fun. :)

UoV r*1

Try it online!

Explanation

UoV r*1  // Implicit: U = first input, V = second input
UoV      // Generate range [U,V).
    r*1  // Reduce by multiplication, starting at 1.

Wow, this seems pathetic compared to the other answers so far. I need to work on Japt some more...

ETHproductions

Posted 2015-12-10T02:46:26.057

Reputation: 47 880

Explanation? :3 – Conor O'Brien – 2015-12-10T03:01:59.167

@CᴏɴᴏʀO'Bʀɪᴇɴ Done :) – ETHproductions – 2015-12-10T03:03:31.543

2Woot, 5K rep! :D – ETHproductions – 2015-12-10T03:09:50.000

7

Seriously, 4 bytes

,ixπ

,         Read list [a,b] from stdin
 i        Flatten it to a b
  x       Pop a,b, push range(a,b)
   π      Pop the list and push its product.

Hex Dump:

2c6978e3

Try it online

quintopia

Posted 2015-12-10T02:46:26.057

Reputation: 3 899

6

Octave, 15 bytes

@(a,b)prod(a:b)

Straightforward. Uses the inclusive range.

lirtosiast

Posted 2015-12-10T02:46:26.057

Reputation: 20 331

6

Haskell, 19 17 bytes

a#b=product[a..b]

Usage example: 2#5-> 120.

nimi

Posted 2015-12-10T02:46:26.057

Reputation: 34 639

You're allowed to choose to include b. – xnor – 2015-12-10T17:06:49.803

@xnor: Ups, must have overlooked that. Thanks! – nimi – 2015-12-10T18:01:11.090

I'm not sure, but I think PPCG allows answers given as expressions. – proud haskeller – 2015-12-11T14:04:30.523

@proudhaskeller: the default is to allow full programs and functions. Snippets, expressions, etc. have to be explicitly permitted in the task description.

– nimi – 2015-12-11T15:26:17.273

5

CJam, 6 19 18 10 bytes

Thanks to Dennis and RetoKoradi for help with golfing!

q~1$-,f+:*

Try it online

Takes input as a b. Calculates PI [a,b).

Note: this program is 6 bytes long, and only works if a and b are positive.

q~,>:*

Try it online

Takes input as a b. Calculates PI [a,b).

GamrCorps

Posted 2015-12-10T02:46:26.057

Reputation: 7 058

q~{_)_W$<}g;]:* saves three bytes. – Dennis – 2015-12-10T05:18:09.760

4q~1$-,f+:* for 10 bytes. – Reto Koradi – 2015-12-10T07:17:49.673

5

Prolog, 45 bytes

Code:

p(A,B,C):-A=B,C=A;D is A+1,p(D,B,E),C is A*E.

Explained:

p(A,B,C):-A=B,      % A is unifiable with B
          C=A       % Unify C with A
          ;         % OR
          D is A+1, % D is the next number in the range
          p(D,B,E), % Recurse on the range after the first element
          C is A*E. % The result C is the product of the first element and the result 
                      of the recursion

Example:

p(5,10,X).
X = 151200

p(-4,-1,X).
X = 24

Emigna

Posted 2015-12-10T02:46:26.057

Reputation: 50 798

5

Bash + GNU utilities, 13

seq -s* $@|bc

Assumes there are no files in the current directory whose names start with -s. Start and end (inclusive) are passed as command-line parameters.

This simply produces the sequence from start to end, separated by *, then pipes to bc for arithmetic evaluation.

Digital Trauma

Posted 2015-12-10T02:46:26.057

Reputation: 64 644

2But I start all my files with -s! :P – Conor O'Brien – 2015-12-10T05:40:55.557

5

MATL (non-competing), 4 bytes

Inclusive Range

2$:p

Try it online!

Explanation

2$: % Implicitly grab two input arguments and create the array input1:input2
p   % Take the product of all array elements

Thanks to @Don Muesli for helping me get the hang of this whole MATL thing.

Suever

Posted 2015-12-10T02:46:26.057

Reputation: 10 257

Nice answer! Since the language postdates the challenge, you can post the answer but perhaps you should indicate it's non-eligible for winning

– Luis Mendo – 2016-03-30T15:40:12.727

Isn't &:p a byte shorter? – James – 2016-07-25T23:23:40.197

@DrGreenEggsandIronMan yea so I guess it's non-competing anyhow so I could shorten it, but at the time I posted my answer we didn't have & – Suever – 2016-07-25T23:24:28.097

4

JavaScript (ES6), 22 bytes

I can't believe none of us JS golfers thought to use recursion...

a=>F=b=>a-b?b*F(b-1):a

Assign to a variable with e.g. var q = a=>F=b=>a-b?b*F(b-1):a, then call like q(2)(5).

ETHproductions

Posted 2015-12-10T02:46:26.057

Reputation: 47 880

4

Brachylog, 3 bytes

⟦₃×

Try it online!

Input is passed as [A,B]. The range is exclusive of B, but could be made inclusive by replacing the with .

Unrelated String

Posted 2015-12-10T02:46:26.057

Reputation: 5 300

3Welcome to PPCG! Nowadays, it doesn't matter when languages are made, so this answer is perfectly competitive. Hope you enjoy your stay! – Conor O'Brien – 2019-02-20T04:45:23.573

Ah, good to know! I guess I've been looking at too many old challenges with answers sorted by votes. – Unrelated String – 2019-02-20T04:46:34.650

@UnrelatedString By the way, if you see those non-competing messages it's perfectly fine to edit them out. – Esolanging Fruit – 2019-02-22T05:42:48.627

4

Jolf, 4 bytes

Try it here!

OrjJ
  jJ two inputs
 r   range between them [j,J)
O    product

Conor O'Brien

Posted 2015-12-10T02:46:26.057

Reputation: 36 228

In modern Jolf, this can be Orj (which automatically is transpiled to Orjx) – Conor O'Brien – 2019-09-18T12:25:33.980

4

Ruby, 22 bytes

->i,n{(i..n).reduce:*}

Ungolfed:

-> i,n {
  (i..n).reduce:* # Product of a range
}

Usage:

->i,n{(i..n).reduce:*}[5,10]
=> 151200

Vasu Adari

Posted 2015-12-10T02:46:26.057

Reputation: 941

1I was thinking about this same solution last night but didn't have the time to write it up. – Alexis Andersen – 2015-12-10T13:59:22.673

4

C, 32 bytes

For [a,b):

f(a,b){return a-b?a*f(a+1,b):1;}

For [a,b] (On Katenkyo's suggestions, 32 bytes again) :

f(a,b){return a<b?a*f(a+1,b):b;}

Sahil Arora

Posted 2015-12-10T02:46:26.057

Reputation: 341

1I found an other solution in C, if you're interested, it's also 32 bytes f(a,b){return a<b?a*f(a+1,b):b;}. :) – Katenkyo – 2015-12-14T15:24:20.583

-5 bytes in gcc with a=... instead of return... – None – 2019-02-22T18:57:16.597

4

05AB1E, 2 bytes (non-competing)

Code:

ŸP

Explanation:

Ÿ   # Inclusive range [input, ..., input]
 P  # Total product of the list
    # Implicit printing top of the stack

Adnan

Posted 2015-12-10T02:46:26.057

Reputation: 41 965

4

J, 8 bytes

[:%/!@<:

Usage

>> f =: [:%/!@<:
>> f 10 5
<< 15120

where >> is STDIN and << is STDOUT.

Explanation

It computes ∏[a,b] as (b-1)!/(a-1)!.

minus_one =: <:
factorial =: !
of        =: @
monadic   =: [:
division  =: %/
f =: monadic division factorial of minus_one

Previous 13-byte version

Written when I had no idea what J even is :p

*/(}.[:>:i.)/

Usage:

   */(}.[:>:i.)/ 5 10
30240

Explanation:

*/            NB. multiply over
  (
   }.         NB. remove [the first x items] from
     [:>:     NB. increment all of
         i.   NB. the numbers from 0 to [y-1]
           )
            / NB. insert the above code into the following numbers

Detailed explanation:

i.10 would produce 0 1 2 3 4 5 6 7 8 9

>:i.10 would make it 1 2 3 4 5 6 6 7 8 9 10

the [: is used to make the ">:" take only one argument (a monad)
because if it takes two arguments, it is a different function.
so [:>:i.10 becomes 1 2 3 4 5 6 7 8 9 10

}. means take away the first [x] items from the following list,
so 5}.1 2 3 4 5 6 7 8 9 10 becomes 6 7 8 9 10

the two slashes "/" in the code are actually the same
for example, */6 7 8 9 10 becomes 6*7*8*9*10

Leaky Nun

Posted 2015-12-10T02:46:26.057

Reputation: 45 011

1Great explanation! – wizzwizz4 – 2016-03-30T07:24:47.750

2You can use [:*/]+i.@- for 10 bytes if you take the range [a, b) as b ([:*/]+i.@-) a such that 10 ([:*/]+i.@-) 5 outputs 15120. – miles – 2016-06-08T01:36:39.493

@miles That answer was written when I didn't know J at all :p – Leaky Nun – 2016-06-08T02:07:00.553

Your 8 byte solution won't work if neither argument is positive. – Dennis – 2016-06-08T03:20:05.750

3

Minkolang 0.14, 7 bytes

nnL$*N.

Try it here.

Explanation

nn         Takes two numbers from input
  L        Pops b,a and pushes a..b
   $*      Product the whole stack
     N.    Output as number and stop.

El'endia Starman

Posted 2015-12-10T02:46:26.057

Reputation: 14 504

3

Python, 52 bytes

Very simple code; a bit too long.

def p(a,b):
 t=1
 for i in range(a,b):t*=i
 return t

Sherlock9

Posted 2015-12-10T02:46:26.057

Reputation: 11 664

3

JavaScript (ES6), 45 41 bytes

Saved 4 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ

(a,b)=>[...Array(b-a)].reduce(x=>x*a++,1)

Seems a little too long...

(a,b)=>           // Define an anonymous function that takes parameters a and b, and returns:
[...Array(b-a)]   // An array of b-a items,
.reduce(          // Reduced by
x=>x*a++          //  multiplying each item with the previous,
,1)               //  starting at 1.

ETHproductions

Posted 2015-12-10T02:46:26.057

Reputation: 47 880

That works? kudos! I don't think you need the y in the reduce mapping, so cut it off at x=>x*a++ – Conor O'Brien – 2015-12-10T03:09:46.070

@CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, that trick works really well! – ETHproductions – 2015-12-10T03:11:05.203

2you should add a semicolon at the end. for the score. – Seadrus – 2015-12-10T03:11:36.523

3

Julia, 16 bytes

f(a,b)=prod(a:b)

Note: if the range object a:b (which is literally stored as a start value and a stop value, and internally includes a "increment by 1 on each step" value) is permitted as the input, then just 4 bytes are required: prod.

Glen O

Posted 2015-12-10T02:46:26.057

Reputation: 2 548

3

Perl 6, 14 bytes

{[*] $^a..$^b}

usage:

my &code = {[*] $^a..$^b}
say code |$_ for (2,5),(5,10),(-4,3),(0,3),(-4,-1);
# 120
# 151200
# 0
# 0
# 24

say chars code 1,10000;
# 35660

If you wanted to exclude the last element use ..^ instead of ..

Brad Gilbert b2gills

Posted 2015-12-10T02:46:26.057

Reputation: 12 713

3

gs2, 4 bytes

Hex: 57 0e 4f 65

Mnemonics: read-nums dump crange product

Try it online!

dump pops a list from the stack and pushes its contents (like ~ in GolfScript), and crange gives [a,b).

Mitch Schwartz

Posted 2015-12-10T02:46:26.057

Reputation: 4 899

3

PowerShell, 30 Bytes

param($a,$b)$a..$b-join'*'|iex

Takes input as two integers, creates a range with .., then -joins that with asterisks, pipes it into Invoke-Expression (similar to eval). The range operator in PowerShell is inclusive.

Pretty competitive with non-golfing languages.

AdmBorkBork

Posted 2015-12-10T02:46:26.057

Reputation: 41 581

3

Java 7, 54 characters

int p(int a,int b){int p=a;while(++a<b)p*=a;return p;}

We cheat the first multiply by assigning it to the temp-product. Then we pre-increment the counter (shamelessly stolen from the input parameter) to skip the first one.

Compare < b instead of <= b - both are to spec, but this saves a character.

Sample:

C:\files>type BadProd.java
class BadProd {
    public static void main(String...args) {
        System.out.println(p(2,5));
        System.out.println(p(5,10));
        System.out.println(p(-4,3));
        System.out.println(p(0,3));
        System.out.println(p(-4,0));

    }
    static int p(int a,int b){int p=a;while(++a<b)p*=a;return p;}
}
C:\files>java BadProd
24
15120
0
0
24

corsiKa

Posted 2015-12-10T02:46:26.057

Reputation: 397

43 bytes if you use a lambda: (a,b)->{int p=a;while(++a<b)p*=a;return p;} – GamrCorps – 2015-12-11T00:40:30.787

Currently on Java 7 - updated to clarify. Good point though! – corsiKa – 2015-12-11T00:42:25.403

Came here to create a Java 7 answer, but you beat me to it. :) I noticed yours is exclusive b and uses a loop though, so I made a (slightly shorter) inclusive b method using recursion. Cool to see more code-golfing Java 7 answers, even though you've answered this more than halve a year ago. ;) +1 from me.

– Kevin Cruijssen – 2016-06-08T11:37:50.893

3

APL (Dyalog Extended), 8 3 bytesSBCS

×/…

Try it online!

range

×/ multiplication across

This is an "atop" so a(×/…)b is ×/a…b.

Adám

Posted 2015-12-10T02:46:26.057

Reputation: 37 779

3

dc, 41 38 37 bytes

This is my first code golf, so bear with me

[lad1+sa*dstlalb>d]sd?sbdst1+saltldxf

It must be saved as a file, and invoked (with bash, so UNIX only) as

dc -f [filename]

It will proceed to wait for input, in the form of a b integers. Note that negative numbers must come as _number.


Alternatively,

echo "X Y [lad1+sa*dstlalb>d]sd?sbdst1+saltdxf" | dc

with X and Y replaced with the two numbers you'd like to product-over-range. This one won't wait unless you don't pipe two numbers.


Explanation:

The recursive macro:
[lad    # load the contents of register a onto the stack, and duplicate it
 1+sa   # Add 1 to the top of the stack (a) and store it in register a
 *dst   # Multiply two off the stack, duplicate and store in register t (stack contains t)
 lalb>d # load a and b, as long as b>a execute d (which is this macro)
 ]sd    # Store that macro in register d
 ?      # Wait for input, hope it is [a b] without braces 
 sbd    # store b, duplicate a (stack == a a) (old: sbddsa)
 st     # store a => t (stack == a)
 1+sa   # add 1 to a and store it in a
 lt     # load t since d expects the total to be on the stack
 ldx    # load d and execute it as a macro
 f      # after d is done recursively calling, t will still be on the stack.
        # Print the stack and close (close is implicit)

There was a removal of a spare duplication and store (dsa)

Delioth

Posted 2015-12-10T02:46:26.057

Reputation: 221

1I believe you can omit the q, since dc automatically terminates when it reaches the end of its input. – Joe – 2016-07-24T19:26:31.140

By the way, another common input method is dc -e "stuff". This will also take input from stdin or piped in from echo. Keep up the good work! dc is my favourite language. – Joe – 2016-07-25T19:00:40.253

2

Keg -hr, 3 bytes

ɧ∑*

Try it online!

Explanation:

ɧ   # Generate inclusive range from two integer inputs
 ∑* # Calculate product of whole stack
    # Output

user85052

Posted 2015-12-10T02:46:26.057

Reputation:

2

W, 3 bytes (inclusive)

.*r

Explanation

ab.   % Generate inclusive range from a to b
   *  % Multiplication
    r % Preserve the operation's action & reduce by it

user85052

Posted 2015-12-10T02:46:26.057

Reputation:

2

Mouse, 36 bytes

?A:?B:A.I:(A.B.<^A.1+A:A.I.*I:)I.!$

This reads two integers from STDIN and prints an integer to STDOUT. This computes the sum over the closed interval, i.e. [a,b] rather than [a,b).

Ungolfed:

? A:             ~ Read an integer from STDIN, assign to A
? B:             ~ Read STDIN, assign B
A. I:            ~ Begin an accumulator at A
( A. B. < ^      ~ While A < B...
  A. 1 + A:      ~ Increment A
  A. I. * I:     ~ I *= A
)
I. !             ~ Print I to STDOUT
$

Alex A.

Posted 2015-12-10T02:46:26.057

Reputation: 23 761

2

LabVIEW, 14 LabVIEW Primitives

Range is exclusive. Creates an array from a to b then multiplies all elements.

Eumel

Posted 2015-12-10T02:46:26.057

Reputation: 2 487

2

JavaScript (ES6), 39

Inclusive range.

(a,b)=>[...Array(b-a)].map(_=>b*=a++)|b

Note: map beats reduce once again

edc65

Posted 2015-12-10T02:46:26.057

Reputation: 31 086

Nice, didn't think of that. +1 – ETHproductions – 2015-12-10T16:05:26.573

2

zsh, 30 bytes

f=({$1..$2})
echo $[${f// /*}]

Sample run:

manatwork% zsh product.zsh 5 10
151200

manatwork

Posted 2015-12-10T02:46:26.057

Reputation: 17 865

24 bytes – GammaFunction – 2019-09-18T08:30:24.250

2

jq, 36 bytes

(35 characters code + 1 character command line option)

reduce range(.[0];.[1])as$i(1;.*$i)

Sample run:

bash-4.3$ bin/jq -s 'reduce range(.[0];.[1])as$i(1;.*$i)' <<< '5 10'
15120

On-line test (Passing -s through URL is not supported – so input passed as [5, 10].)

manatwork

Posted 2015-12-10T02:46:26.057

Reputation: 17 865

2

TI-Basic, 14 11 bytes

Prompt A,B:prod(randIntNoRep(A,B

SuperJedi224

Posted 2015-12-10T02:46:26.057

Reputation: 11 342

2

Fortran, 44 bytes

Finally a use for those pesky implicit types.

function j(k,l)
j=1
do i=k,l
j=j*i
enddo
end

Test program:

program testProduct
  integer :: a, k, l
  k = -4
  l = -1
  a = j(k,l)
  print*,a
end program testProduct

toni

Posted 2015-12-10T02:46:26.057

Reputation: 121

2

Vitsy, 14 bytes

Note to self: add range

Expects input as b a.

D{-\[D1+]l1-\*
D               Duplicate the top input.
 {-\[   ]       Repeat the stuff in the brackets by the difference between the 
                inputs.
     D1+        Duplicate, add one.
                I now have the range [a,b].
         l1-\*  Multiply all the items together.

This is a function in Vitsy that will leave the product of the range [a,b] on the stack. "But how do I test it?!?" I hear you ask?

Concatenate N. c:

Try it online!

Addison Crump

Posted 2015-12-10T02:46:26.057

Reputation: 10 763

3k rep for you ! :D – Conor O'Brien – 2015-12-11T12:20:49.930

\o/ @CᴏɴᴏʀO'Bʀɪᴇɴ – Addison Crump – 2015-12-11T12:35:41.067

2

dc, 27 bytes

Input assumes a is on top of the main stack and b is under it

dsar[dsc*lc1-dla<A]sAlAxrp

Ungolfed:

dsa        # duplicate 'a', store a copy in register a
r          # reverse top two items on stack
[          # start macro definition 
  dsc      # duplicate counter, store in register c 
           #  ('b' is the initial counter value)
  *        # pop top two elements of stack, multiply and push result
  lc       # copy the stored counter to the stack
  1- d     # decrement and duplicate it
  la       # copy 'a' to the stack
  <A       # if 'a' is < the counter, run macro A
]sA        # store this macro as A
lAx        # execute macro A
r          # reverse top two elements of stack
p          # pop/print the result

SnoringFrog

Posted 2015-12-10T02:46:26.057

Reputation: 1 709

2

Milky Way 1.5.17, 28 bytes

1%{¢¢L§{?{¢1-e__^}}£*}!

Explanation

1          1             # push integer to the stack
 %{                £ }   # for loop
   ¢¢     ¢              # read a single line of input from the command line
     L                   # push a Pythonic range(0, TOS + 1)
      §{          }      # mapping
        ?{    __ }       # if-else statement
            -            # subtract the STOS from the TOS
             e           # order the TOS and STOS (greater-than)
                ^        # pop the TOS
                      !  # output the TOS

Usage

$ ./mw <path-to-code> -i <input>

Example:

$ ./mw test.mwg -i "2
5"

Milky Way takes line breaks literally. \n is not interpreted as a line break. In future versions, this will be changed.

Zach Gates

Posted 2015-12-10T02:46:26.057

Reputation: 6 152

2

Arcyóu, 17 bytes

(F(a b)(r *(_ a b

This includes a but excludes b.

Explanation:

(F(a b)    ; Anonymous function F(a, b)
  (r *     ; Reduce by multiplication
    (_ a b ; Range from a to b

jqblz

Posted 2015-12-10T02:46:26.057

Reputation: 2 062

2

PlatyPar, 4 bytes

_XF*

_ gets the range [a,b), X expands it onto the stack, and F* folds multiplication over the range. Try it online!

Cyoce

Posted 2015-12-10T02:46:26.057

Reputation: 2 690

2

Rust, 52 51 bytes

fn p(mut a:i32,b:i32)->i32{for i in a+1..b{a*=i;}a}

Usage (+ ungolfed version) as follows:

fn p(mut a:i32, b:i32) -> i32 {
    for i in a+1..b {
        a *= i;
    }
    a
}

fn main() {
    println!("{}", p(2, 5));
    println!("{}", p(5, 10));
    println!("{}", p(-4, 3));
    println!("{}", p(-4, 0));
}

Uses the current stable version of Rust (1.5.0)

S22h

Posted 2015-12-10T02:46:26.057

Reputation: 151

1fn p(a:i32,b:i32)->i32{(a..b).fold(1,|a,b|a*b)}. In a future version of Rust: fn p(a:i32,b:i32)->i32{(a..b).product()}. – Shepmaster – 2016-01-23T20:19:56.210

2

PHP, 42 Bytes

<?=array_product(range($ARGV[1],$ARGV[2]))

<?=                         // Open file, '=' is shorthand for 'echo'
array_product(              // Get product of array
range($argv[1],$argv[2])    // array is range from a to b
)

Xanderhall

Posted 2015-12-10T02:46:26.057

Reputation: 1 236

2

Swift, 26 58 bytes

func p(a:Int,b:Int)->Int{return(a+1..<b).reduce(a){$0*$1}}

John McDowall

Posted 2015-12-10T02:46:26.057

Reputation: 161

1

Pushy, 8 bytes

Non-competing as the language postdates the challenge.

w-:&h;P#

Try it online!

Most of the code is building the range, as there is a builtin for finding the product (P).

w          \ Mirror stack, yielding [a, b, a]
 -         \ Pop (b, a) and push b - a, the difference
  :  ;     \ That many times do:
   &h      \   Push last item +1
      P#   \ Print product

The w-:&h; is essentially a long-winded binary range function, as Pushy only has unary range commands.

FlipTack

Posted 2015-12-10T02:46:26.057

Reputation: 13 242

1

tcl, 55

incr p
while \$a<$b {set p [expr $p*$a];incr a}
puts $p

demo

sergiol

Posted 2015-12-10T02:46:26.057

Reputation: 3 055

1

Ahead, 7 bytes

Input is taken as two numbers on standard in. Range is [a,b].

IIEK*O@

II       read two ints and push to stack
  E      expand range between top two stack items
   K     reduce stack by...
    *    multiplying
     O   pop and print number
      @  terminate

Try it online!

snail_

Posted 2015-12-10T02:46:26.057

Reputation: 1 982

1

F# (.NET Core), 27 bytes

fun a b->Seq.fold(*)1[a..b]

Try it online!

LSM07

Posted 2015-12-10T02:46:26.057

Reputation: 191

1

Clam, 5 bytes

p;Brr

Explanation

p     - Print...
 ;    - Product of...
  B   - Range...
   r  - Next input
    r - Next input

Skidsdev

Posted 2015-12-10T02:46:26.057

Reputation: 9 656

1

Python 2, 30 bytes

f=lambda a,b:b<a or a*f(a+1,b)

Try it online!

Range is inclusive (e.g., f(2,5) => 120).

Chas Brown

Posted 2015-12-10T02:46:26.057

Reputation: 8 959

1

GolfScript, 8 bytes

Idea copied from the gs2 solution.

~,\>{*}*

Try it online!

Explanation

~        # Dump the input,            e.g. 2 4
 ,       # Generate range from 0 to input: 2 [0 1 2 3 4]
  \      # Swap the stack                : [0 1 2 3 4] 2
   >     # Keep all those that are larger: [2 3 4]
    {*}* # Reduce by multiplication      : 24

user85052

Posted 2015-12-10T02:46:26.057

Reputation:

1

golflua, 26 characters

\p(f,t)~@i=f+1,t f=f*i$~f$

Sample run:

Lua 5.2.2  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> \p(f,t)~@i=f+1,t f=f*i$~f$
> w(p(5, 10))
151200

manatwork

Posted 2015-12-10T02:46:26.057

Reputation: 17 865

1

C#, 66 bytes

Not great, but not too bad.

int d(int a,int b)=>Enumerable.Range(a,b-a).Aggregate((x,y)=>x*y);

DLeh

Posted 2015-12-10T02:46:26.057

Reputation: 1 111

I believe you need to include the using System.Linq; in order to use aggregate. – None – 2016-07-25T22:37:48.270

1

Hassium, 49 Bytes

func f(a,b){t=a;for(x=a+1;x<b;x++)t=t*x;print(t)}

See expanded and run online with test case here

Jacob Misirian

Posted 2015-12-10T02:46:26.057

Reputation: 737

1

Befunge, 51 bytes

 v          @.$<
v>&20p&30p1
>20g*20g:30g-!#^_1+20p

This can probably be optimised with some stack manipulation wizardry.
I went for put and get instructions instead. Might get back to it later on.
Also fails with negative numbers, since AFAIK Befunge doesn't handle them, instead looping back to maxint.

karhell

Posted 2015-12-10T02:46:26.057

Reputation: 411

1

, 4 chars / 11 bytes

⨴⩥…ï

Try it here (Firefox only).

Creates an exclusive range from the array input, and multiplies everything in the resulting range. (Note that although the interpreter is using v2 of the language, this code still works in v1.)

Mama Fun Roll

Posted 2015-12-10T02:46:26.057

Reputation: 7 234

1

Python 56

a=input()
b=input()
print reduce(int.__mul__,range(a,b))

epson121

Posted 2015-12-10T02:46:26.057

Reputation: 171

1print reduce(int.__mul__,range(input(),input())) is shorter. – mbomb007 – 2016-07-01T21:28:56.013

1

Detour, 3 bytes (non-competing)

rP.

Try it online!

Same as @quartata's Jelly answer, except . is required to output the result so it doesn't wrap back around to r.
This was not intended to be a golfing language, but the 1-character commands necessary to operate on a 2d grid make small challenges like this really short.

Cyoce

Posted 2015-12-10T02:46:26.057

Reputation: 2 690

1

CoffeeScript, 46 45 44 29 bytes

Inclusive range

29 bytes version (anonymous function):

(a,b)->c=a;c*=++a while a<b;c

Equivalent to next JS code:

(function(a, b) {
    var c;
    c = a;
    while (a < b) {
        c *= ++a;
    }
    return c;
});

44 bytes version (prompt()):

alert [prompt()..prompt()].reduce (a,b)->a*b

45 bytes version:

alert [prompt()..prompt()].reduce((a,b)->a*b)

46 bytes version:

alert([prompt()..prompt()].reduce((a,b)->a*b))

username.ak

Posted 2015-12-10T02:46:26.057

Reputation: 411

1

Reng v.3, 25 bytes

This is encoded in ISO 8859-1, and you can try it out at the new IO page!

ii#x:1+::xe)2(¿Bh$1¶a*¡n~

Is an inclusive range.

ii takes 2 inputs, and stores the second one (the maximum) in x. :1+:: sets a to a (a+1) (a+1) (a+1). xe sets the TOS to the equality of the counter (a+1) and )2( sets the STOS to 2. ¿ pops two numbers and, if the TOS is true, the pointer moves STOS times. Otherwise, we just go forward. In the event that we have not reached the maximum, Bh goes back 11 units. $ drops the excess counter from the TOS once we are done looping. sets the default pop from an empty stack to 1, so we can use a double-sided mirror loop to multiply everything. a is a one-sided mirror, and * multiplies values. ¡ mirrors until the stack's length is 1. Once the length is 1, n~ is met and outputs the result and exits the program.

Conor O'Brien

Posted 2015-12-10T02:46:26.057

Reputation: 36 228

1

Factor, 79 43 29 bytes

Hooray for auto use!

It's quite elegant, really. A lambda, that goes on the stack.

[ 1 - [a,b] 1 [ * ] reduce ]

cat

Posted 2015-12-10T02:46:26.057

Reputation: 4 989

1

Mathcad, 4 "bytes"

Uses the built-in Iterated Product Operator, which is entered from the keyboard by ctl-#. Type k into the iterator and expression placeholders and then type the evaluation operator (=), giving a total of 4 "bytes" where one byte is taken to be the number of characters needed to enter an expression.

enter image description here

Stuart Bruff

Posted 2015-12-10T02:46:26.057

Reputation: 501

1

Matricks, 24 bytes

Matricks is a new esolang I invented to deal with matrices. Run like: python matricks.py [[<num1>,<num2>]]

mg:;+c:1:g:1;-g:;;kp{};;

This is a simple answer. Matricks has a built-in for taking the product of an array, p, so all I need to do is make the range with the constructor, m

Blue

Posted 2015-12-10T02:46:26.057

Reputation: 1 986

1

Java 7, 49 48 bytes

int c(int a,int b){return-~a!=b?a*c(a+1,b):a*b;}

corsiKa's answer is exclusive, mine is inclusive (and slightly shorter by using recursion instead of a loop).

Explanation:

Try it here.

int c(int a,int b){  // Method with two integer parameters and integer return-type
  return-~a!=b?      //  If `a+1` is not equal to `b`
         a*c(a+1,b)  //   Return `a` multiplied by the recursive call with `a+1,b`
        :            //  Else:
         a*b;        //   Return `a*b`
}                    // End of method

Kevin Cruijssen

Posted 2015-12-10T02:46:26.057

Reputation: 67 575

1

k/kona, 8 bytes

*/a+!b-a

Let's break this down: k reads right-to-left, so:

b-a finds the difference between b and a, to give the number of numbers required

!(b-a) generates a list from 0 to (b-a), giving the range [0, (b-a))

a+(!b-a) adds a to each element of the list, to get the range [a, b)

*/(a+!b-a) applies multiplication over all elements of the list; * is the multiply operator, and / is the over adverb, which is like a map/reduce function, applying its left-hand argument over all elements of its right-hand argument.

Simon Major

Posted 2015-12-10T02:46:26.057

Reputation: 401

1

Racket (scheme), 29 bytes

Functional programming woot

Apply applies a function to all elements of a list, and range creates a list ranging from a to b. The function being applied is *. Exclusive.

(λ(a b)(apply *(range a b)))

kronicmage

Posted 2015-12-10T02:46:26.057

Reputation: 111

1

Fith, 17 bytes (non-competing)

This language was created after the challenge.

{ range product }

Anonymous function. Excludes b. Pretty self-explanatory.

Stack effect: a b -- *[a,b)

jqblz

Posted 2015-12-10T02:46:26.057

Reputation: 2 062

Is this your language? :3 – Conor O'Brien – 2016-06-27T00:31:33.900

@CᴏɴᴏʀO'Bʀɪᴇɴ Yes it is! Mainly inspired by Factor and Haskell. It's concatenative/stack-based. – jqblz – 2016-06-27T01:02:09.320

1I guess then {range would be one token, so the whitespace is necessary? – Conor O'Brien – 2016-06-27T02:03:51.407

@CᴏɴᴏʀO'Bʀɪᴇɴ Unfortunately, yes. – jqblz – 2016-06-27T03:05:13.977

Are you sure it's not just a successor to Forth? :P – mbomb007 – 2016-07-01T21:27:38.930

@mbomb007 It's that too :) – jqblz – 2016-07-03T03:27:56.170

1

><>, 33 bytes

 1&:@$:@)?\&n;
:$@:+1&*&:/?@@$@)@

My first fish attempt.

Inclusive range
Assumes a and b are on the stack.

Emigna

Posted 2015-12-10T02:46:26.057

Reputation: 50 798

1

Perl 6 - 15 bytes

{[*] $^a..$^b}

Usage:

> {[*] $^a..$^b}(2,5)
120

malkaroee

Posted 2015-12-10T02:46:26.057

Reputation: 332

1

Forth, 33 bytes

Pretty simple looping program.

: f DUP ROT DO DUP I * LOOP ; f .

Try it online

mbomb007

Posted 2015-12-10T02:46:26.057

Reputation: 21 944

1

JavaScript (using external library) (31 bytes)

 (a,b)=>_.RangeTo(a,b).Product()

Link to lib: https://github.com/mvegh1/Enumerable/

Explanation of code: Anonymous method accepts low bound and high bound for range, and uses built in .Product method to produce the product for that range

enter image description here

applejacks01

Posted 2015-12-10T02:46:26.057

Reputation: 989

1

C#, 56 Bytes

int f(int a,int b){var r=1;for(;a<b;a++)r*=a;return r;}

user19547

Posted 2015-12-10T02:46:26.057

Reputation:

1

Excel, 37 bytes

=PRODUCT(A2-ROW(OFFSET(A1,,,A2-A1)))

Data will be a in A1 and b in A2.

The above should be entered as an array formula (ctrl_shift_enter) in any other cell. The result is exclusive of b.

Joffan

Posted 2015-12-10T02:46:26.057

Reputation: 832

0

Triangular, 21 20 bytes

$\S=t$iUprP%..%/*U:<

Try it online!

Takes input with order b, a from standard in.

Ungolfed: (Explanation to be added later)

      $ 
     \ S 
    = t $ 
   i U p r 
  P % . . % 
 / * U : <


Previous Version (21 bytes):
1\P\p$?Ud$=0%)(/P*U:<

Reinstate Monica

Posted 2015-12-10T02:46:26.057

Reputation: 1 382

0

JavaScript (ES6), 25 bytes

f=(a,b)=>a-b?a*f(a+1,b):b

Inclusive.

Naruyoko

Posted 2015-12-10T02:46:26.057

Reputation: 459

0

Perl 5 -p, 22 bytes

$_=eval join'*',$_..<>

Try it online!

Xcali

Posted 2015-12-10T02:46:26.057

Reputation: 7 671

0

Perl 6, 14 bytes

{[*] [...] @_}

Try it online!

Reduce the two inputs by range, then reduces by multiplication.

Jo King

Posted 2015-12-10T02:46:26.057

Reputation: 38 234