48
\$\begingroup\$

Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[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>

\$\endgroup\$
4
  • 2
    \$\begingroup\$ I'm answering this in TI-BASIC tomorrow. \$\endgroup\$ Dec 10, 2015 at 2:48
  • \$\begingroup\$ @SuperJedi224 Good luck ;) \$\endgroup\$ Dec 10, 2015 at 2:48
  • \$\begingroup\$ Can the input be taken as b, a? \$\endgroup\$
    – FlipTack
    Feb 12, 2017 at 20:01
  • \$\begingroup\$ @FlipTack yes you can \$\endgroup\$ Feb 12, 2017 at 20:03

114 Answers 114

2
\$\begingroup\$

Clam, 5 bytes

p;Brr

Explanation

p     - Print...
 ;    - Product of...
  B   - Range...
   r  - Next input
    r - Next input
\$\endgroup\$
2
\$\begingroup\$

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

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

Keg -hr, 3 bytes

ɧ∑*

Try it online!

Explanation:

ɧ   # Generate inclusive range from two integer inputs
 ∑* # Calculate product of whole stack
    # Output
\$\endgroup\$
0
2
\$\begingroup\$

W, 3 bytes (inclusive)

.*r

Explanation

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

Kotlin, 30 bytes

Range is inclusive

{a,b->(a..b).reduce{c,d->c*d}}

Try it online!


Kotlin, 21 bytes

If you can take input as an IntRange:

{it.reduce{c,d->c*d}}

Try it online!

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

Vyxal, 2 bytes

Range of a to b, then product

Try it!

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

Pyth, 4 bytes

*F}F

Test suite

Range is inclusive.

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

Pip, 6 bytes

$*Ya,b

Try it online!

-1 byte from DLosc.

\$\endgroup\$
2
  • \$\begingroup\$ I'm gonna guess that this is a yank \$\endgroup\$
    – Razetime
    Oct 8, 2021 at 4:36
  • 2
    \$\begingroup\$ Yep \$\endgroup\$
    – DLosc
    Oct 8, 2021 at 4:42
2
\$\begingroup\$

PostScript, 27 bytes

{1 exch 1 4 1 roll{mul}for}

Anonymous function for inclusive product. Takes two inputs from the stack and leaves output on the stack.

(Usage: e.g., 5 10 {1 exch 1 4 1 roll{mul}for} exec = prints 151200.)

Try it online!

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

HBL, 2.5 bytes

*(0.,

Uses inclusive range. Try it at HBL Online!

Explanation

After parentheses autocompletion, we have '(*(0.,)):

'(*(0.,))
'(      )  Define a function which returns
  *        the product of
   (0  )   the range from
     .     the first argument to
      ,    the second argument
\$\endgroup\$
2
\$\begingroup\$

Fig, \$2\log_{256}(96)\approx\$ 1.646 bytes

rR

See the README to see how to run this

Calculates using the range [a, b] (because of bug). Explanation:

rR # Takes input as "a b"
 R # Range [a, b]
r  # Product
\$\endgroup\$
12
  • \$\begingroup\$ I am very sceptical about the 1.646-byte claim, which seems impossible as it isn't an integer number of bits. The size of a program for code-golf is the size of the program when it is stored. Other sub-byte-token languages (like Nibbles or seven, for instance) implement ways to actually store the program in the indicated number of bytes/bits, and to do this can even 'cost' extra bits. Simply declaring that - because you've elected to use only 96 characters - the code 'size' is a multiple of log256(96) isn't sufficient. \$\endgroup\$ Jul 25 at 10:17
  • \$\begingroup\$ I think it would be fairer to score this with the smallest number of bytes/bits that you can actually store the program in (if the 'Fig' interpreter implements base-96 encoding of the program, and is also able to write/read this as binary bits, then this program could be 13 bits, which could even save you 0.17 bits). \$\endgroup\$ Jul 25 at 10:17
  • 1
    \$\begingroup\$ @DominicvanEssen chat, currently accepted rule \$\endgroup\$
    – Seggan
    Jul 26 at 14:59
  • 1
    \$\begingroup\$ @Deadcode oops, thats a bug in my input evaluator. You can append N<number> for the same effect \$\endgroup\$
    – Seggan
    Jul 26 at 19:38
  • 1
    \$\begingroup\$ @Deadcode as in N1, not N-1. N is negation \$\endgroup\$
    – Seggan
    Jul 26 at 20:09
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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);
\$\endgroup\$
1
  • \$\begingroup\$ I believe you need to include the using System.Linq; in order to use aggregate. \$\endgroup\$
    – user19547
    Jul 25, 2016 at 22:37
1
\$\begingroup\$

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

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

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.

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

Python 56

a=input()
b=input()
print reduce(int.__mul__,range(a,b))
\$\endgroup\$
1
  • 1
    \$\begingroup\$ print reduce(int.__mul__,range(input(),input())) is shorter. \$\endgroup\$
    – mbomb007
    Jul 1, 2016 at 21:28
1
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟, 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.)

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

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.

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

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))
\$\endgroup\$
1
\$\begingroup\$

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.

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

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

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

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 ]
\$\endgroup\$
1
\$\begingroup\$

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

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

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.

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

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)))
\$\endgroup\$
1
\$\begingroup\$

Perl 6 - 15 bytes

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

Usage:

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

Forth, 33 bytes

Pretty simple looping program.

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

Try it online

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

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

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

C#, 56 Bytes

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

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.

\$\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.