39
\$\begingroup\$

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>

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

83 Answers 83

3
\$\begingroup\$

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

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

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.

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

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

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)

\$\endgroup\$
  • 1
    \$\begingroup\$ I believe you can omit the q, since dc automatically terminates when it reaches the end of its input. \$\endgroup\$ – Joe Jul 24 '16 at 19:26
  • \$\begingroup\$ 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. \$\endgroup\$ – Joe Jul 25 '16 at 19:00
2
\$\begingroup\$

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

zsh, 30 bytes

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

Sample run:

manatwork% zsh product.zsh 5 10
151200
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 39

Inclusive range.

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

Note: map beats reduce once again

\$\endgroup\$
  • \$\begingroup\$ Nice, didn't think of that. +1 \$\endgroup\$ – ETHproductions Dec 10 '15 at 16:05
2
\$\begingroup\$

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

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!

\$\endgroup\$
  • \$\begingroup\$ 3k rep for you ! :D \$\endgroup\$ – Conor O'Brien Dec 11 '15 at 12:20
  • \$\begingroup\$ \o/ @CᴏɴᴏʀO'Bʀɪᴇɴ \$\endgroup\$ – Addison Crump Dec 11 '15 at 12:35
2
\$\begingroup\$

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

LabVIEW, 14 LabVIEW Primitives

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

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

TI-Basic, 14 11 bytes

Prompt A,B:prod(randIntNoRep(A,B
\$\endgroup\$
2
\$\begingroup\$

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.

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

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

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)

\$\endgroup\$
  • 1
    \$\begingroup\$ fn 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()}. \$\endgroup\$ – Shepmaster Jan 23 '16 at 20:19
2
\$\begingroup\$

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!

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

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

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

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

Swift, 26 58 bytes

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

Keg, 7 bytes (SBCS on wiki)

Inclusive range.

¿¿ɧ∑*).

Explanation:

¿¿ɧ#     Generate inclusive range from two integer inputs
   ∑*)#  Calculate product of whole stack
      .# Output
\$\endgroup\$
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\$
  • \$\begingroup\$ I believe you need to include the using System.Linq; in order to use aggregate. \$\endgroup\$ – JustinM - Reinstate Monica Jul 25 '16 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
    \$\begingroup\$ print reduce(int.__mul__,range(input(),input())) is shorter. \$\endgroup\$ – mbomb007 Jul 1 '16 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\$
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\$

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.