# Product over a range

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.

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.

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

• I'm answering this in TI-BASIC tomorrow. – SuperJedi224 Dec 10 '15 at 2:48
• @SuperJedi224 Good luck ;) – Conor O'Brien Dec 10 '15 at 2:48
• Can the input be taken as b, a? – FlipTack Feb 12 '17 at 20:01
• @FlipTack yes you can – Conor O'Brien Feb 12 '17 at 20:03

# 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

• I doubt this is beatable... – kirbyfan64sos Dec 10 '15 at 2:52
• @kirbyfan64sos you jelly? – Aaron Dec 10 '15 at 13:23

## ArnoldC, 522 511 bytes

First post on codegolf !

I had fun doing this. Exclusive range.

LISTEN TO ME VERY CAREFULLY f
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

• Hahaha... I am stil laughing – rpax Dec 10 '15 at 20:23
• but an explanation would be great – rpax Dec 10 '15 at 20:25
• Here it is converted and indented using this as reference – Bijan Dec 10 '15 at 23:22
• Which interpreter are you using? – lirtosiast Dec 10 '15 at 23:58
• The official one. You're right about @NO PROBLEMO and 1 (not 0 ;) ) – Zycho Dec 11 '15 at 9:12

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

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

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


• Program size is counted by this scoring method. – GamrCorps Dec 10 '15 at 23:47
• Dammit, you got to it before I did. :I – Addison Crump Dec 11 '15 at 11:25
• You need to specify snapshot version, i.e. 15w46a or something. – Addison Crump Dec 11 '15 at 11:26
• Minecraft :D LoL, golfing in Minecraft :D – username.ak Feb 3 '16 at 10:07

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

• It took me a while to figure out for myself, so I'm gonna post it here: Each function in TI-BASIC is one byte. – Nic Hartley Dec 11 '15 at 20:13
• @QPaysTaxes Lots of them do, but not all of them. % is two bytes. – mbomb007 Dec 11 '15 at 21:20

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

• You 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 Dec 10 '15 at 3:32
• Crossed out 44 still looks like 44. – a spaghetto Dec 10 '15 at 3:45

## Pyth, 5 bytes

*FrQE


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

Uses exclusive range.

• *FrFQ is equivalent but with different input, just for fun :) – FryAmTheEggman Dec 10 '15 at 3:24

# Mathematica, 15 bytes

1##&@@Range@##&


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

#2!/(#-1)!&

• Even shorter for non-negative integers: #2!#/#!& – Anders Kaseorg Mar 25 '16 at 22:52

# R, 22 bytes

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


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

• Wow. That's impressive! – Conor O'Brien Dec 10 '15 at 12:13
• Aw man, I thought of this exact solution while trying to golf mine just now... +1 – ETHproductions Dec 10 '15 at 16:04
• This one is even shorter with 25 characters: f=(a,b)=>a<b?a*f(a+1,b):1 – Matthias Burtscher May 14 at 18:26

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

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

• Explanation? :3 – Conor O'Brien Dec 10 '15 at 3:01
• @CᴏɴᴏʀO'Bʀɪᴇɴ Done :) – ETHproductions Dec 10 '15 at 3:03
• Woot, 5K rep! :D – ETHproductions Dec 10 '15 at 3:09

a#b=product[a..b]


Usage example: 2#5-> 120.

• You're allowed to choose to include b. – xnor Dec 10 '15 at 17:06
• @xnor: Ups, must have overlooked that. Thanks! – nimi Dec 10 '15 at 18:01
• I'm not sure, but I think PPCG allows answers given as expressions. – proud haskeller Dec 11 '15 at 14:04
• @proudhaskeller: the default is to allow full programs and functions. Snippets, expressions, etc. have to be explicitly permitted in the task description. – nimi Dec 11 '15 at 15:26

# 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


## Octave, 15 bytes

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


Straightforward. Uses the inclusive range.

## CJam, 61918 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). • q~{_)_W$<}g;]:* saves three bytes. – Dennis Dec 10 '15 at 5:18
• q~1$-,f+:* for 10 bytes. – Reto Koradi Dec 10 '15 at 7:17 # 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.

• But I start all my files with -s! :P – Conor O'Brien Dec 10 '15 at 5:40

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

• 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 Mar 30 '16 at 15:40
• Isn't &:p a byte shorter? – DJMcMayhem Jul 25 '16 at 23:23
• @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 Jul 25 '16 at 23:24

# Jolf, 4 bytes

Try it here!

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


# 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

• I was thinking about this same solution last night but didn't have the time to write it up. – Alexis Andersen Dec 10 '15 at 13:59

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

• I 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 Dec 14 '15 at 15:24
• -5 bytes in gcc with a=... instead of return... – user77406 Feb 22 at 18:57

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

# Brachylog, 3 bytes (non-competing?)

⟦₃×


Try it online!

Input is passed as [A,B]. The range is exclusive of B, but could be made inclusive by replacing the ₃ with ₂. Probably non-competing, as I haven't been able to find when in 2015 Brachylog was invented, and it's probably been updated substantially since then.

• Welcome 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 Feb 20 at 4:45
• Ah, good to know! I guess I've been looking at too many old challenges with answers sorted by votes. – Unrelated String Feb 20 at 4:46
• @UnrelatedString By the way, if you see those non-competing messages it's perfectly fine to edit them out. – Esolanging Fruit Feb 22 at 5:42

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


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

• 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 Dec 10 '15 at 3:09
• @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, that trick works really well! – ETHproductions Dec 10 '15 at 3:11
• you should add a semicolon at the end. for the score. – Seadrus Dec 10 '15 at 3:11

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

# 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
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;}
}
24
15120
0
0
24

• 43 bytes if you use a lambda: (a,b)->{int p=a;while(++a<b)p*=a;return p;} – GamrCorps Dec 11 '15 at 0:40
• Currently on Java 7 - updated to clarify. Good point though! – corsiKa Dec 11 '15 at 0:42
• 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 Jun 8 '16 at 11:37

# 05AB1E, 2 bytes (non-competing)

Code:

ŸP


Explanation:

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