| Bytes | Lang | Time | Link |
|---|---|---|---|
| 029 | Swift 6 | 250429T180904Z | macOSist |
| 057 | Tcl | 170619T104235Z | sergiol |
| 014 | Raku Perl 6 rakudo | 250415T172901Z | xrs |
| 031 | AWK | 250414T204001Z | xrs |
| 004 | ☾ | 250414T190135Z | Joao-3 |
| 016 | ARBLE | 250414T015815Z | ATaco |
| 056 | SAKO | 250320T205354Z | Acrimori |
| 009 | Juby | 230905T163732Z | Jordan |
| 005 | Itr | 230814T155716Z | bsoelch |
| 076 | Pascal | 230905T064547Z | Kai Burg |
| 007 | BQN | 230605T023728Z | chunes |
| 029 | ><> Fish | 230603T210532Z | chunes |
| 002 | Thunno 2 | 230603T183628Z | The Thon |
| 002 | Pyt | 230213T024321Z | Kip the |
| nan | HP48 User RPL | 230213T023728Z | gildux |
| 012 | Arturo | 230213T014921Z | chunes |
| 002 | 05AB1E | 160130T174944Z | Adnan |
| 004 | MATL | 160326T011926Z | Suever |
| 034 | Knight | 220801T212657Z | naffetS |
| 030 | Kotlin | 220728T230602Z | Eric Xue |
| 016 | Perl 5 MListUtil=product p | 190514T193542Z | Xcali |
| nan | Fig | 220722T212758Z | Seggan |
| 128 | Regex 🐇 PCRE2 v10.35 or later | 220726T110544Z | Deadcode |
| 255 | Nibbles | 220713T153045Z | Dominic |
| 025 | HBL | 211201T223902Z | DLosc |
| 012 | APL | 220712T191919Z | Vadim Tu |
| 011 | Ly | 211106T074944Z | cnamejj |
| 011 | K ngn/k | 220505T140441Z | oeuf |
| 019 | Desmos | 220503T191013Z | naffetS |
| 027 | PostScript | 220502T072537Z | bartysla |
| 047 | Nim | 220502T065253Z | Qaziquza |
| 023 | dc | 211107T162244Z | Ritwin |
| 002 | Husk | 211010T172639Z | scpchick |
| 010 | x8616 machine code | 211010T192443Z | 640KB |
| 012 | O | 211008T093747Z | wasif |
| 006 | Pip | 200905T042634Z | Razetime |
| 026 | Branch | 210420T060350Z | hyperneu |
| 012 | Factor + math.unicode | 210420T055536Z | chunes |
| 004 | Pyth | 210420T055328Z | hakr14 |
| 002 | Vyxal | 210420T054458Z | wasif |
| 021 | R | 200907T162548Z | DLosc |
| 009 | Scala | 200905T202407Z | user |
| 005 | Arn | 200905T151401Z | ZippyMag |
| 020 | Charcoal | 200905T060433Z | lyxal |
| nan | 200305T094439Z | Praveen | |
| 030 | Kotlin | 200305T082501Z | snail_ |
| 037 | C# Visual C# Interactive Compiler | 200305T072054Z | Jirka Pi |
| 013 | Gol><> | 200305T065726Z | Bubbler |
| 003 | W | 191214T135228Z | user8505 |
| 003 | Keg hr | 190917T133118Z | user8505 |
| 008 | GolfScript | 200117T040756Z | user8505 |
| 003 | APL Dyalog Extended | 160608T184741Z | Adá |
| 020 | Triangular | 190503T114028Z | squid |
| 003 | Brachylog | 190220T043853Z | Unrelate |
| 030 | Python 2 | 190917T224030Z | Chas Bro |
| 014 | Perl 6 | 190516T004301Z | Jo King |
| 025 | JavaScript ES6 | 190503T195302Z | Naruyoko |
| 005 | Clam | 190502T184531Z | Mayube |
| 027 | F# .NET Core | 190424T012529Z | LSM07 |
| 007 | Ahead | 190222T051844Z | snail_ |
| 048 | Java 7 | 160608T113526Z | Kevin Cr |
| 008 | Pushy | 170212T194608Z | FlipTack |
| 022 | JavaScript ES6 | 170211T232425Z | ETHprodu |
| 037 | Excel | 160725T231642Z | Joffan |
| 056 | C# | 160725T223521Z | user1954 |
| 031 | JavaScript using external library | 160725T144911Z | applejac |
| 037 | dc | 160701T200405Z | Delioth |
| 033 | Forth | 160701T215407Z | mbomb007 |
| 015 | Perl 6 | 160630T133455Z | malkaroe |
| 058 | Swift | 160629T095407Z | John McD |
| 033 | ><> | 160629T093838Z | Emigna |
| 017 | Fith | 160626T235147Z | jqkul |
| 029 | Racket scheme | 160609T132301Z | Simon Ze |
| 042 | PHP | 160608T161500Z | Xanderha |
| 008 | k/kona | 160608T150143Z | Simon Ma |
| 008 | J | 160330T064713Z | Leaky Nu |
| 024 | Matricks | 160608T012124Z | Blue |
| 029 | Factor | 160326T154709Z | cat |
| 004 | Mathcad | 160326T183037Z | Stuart B |
| 025 | Reng v.3 | 160325T215510Z | Conor O& |
| 036 | jq | 151210T103840Z | manatwor |
| 029 | CoffeeScript | 160203T100933Z | username |
| 003 | Detour | 160129T023746Z | Cyoce |
| 411 | 𝔼𝕊𝕄𝕚𝕟 | 151229T223755Z | Mama Fun |
| 056 | Python | 160116T151117Z | epson121 |
| 002 | Jelly | 151210T024638Z | a spaghe |
| 004 | PlatyPar | 151216T040226Z | Cyoce |
| 013 | Bash + GNU utilities | 151210T053908Z | Digital |
| 032 | C | 151210T200213Z | Sahil Ar |
| 051 | Rust | 151216T100045Z | S22h |
| 017 | Arcyóu | 151214T085506Z | jqkul |
| 028 | Milky Way 1.5.17 | 151211T211055Z | Zach Gat |
| 011 | TIBasic | 151210T110928Z | SuperJed |
| 014 | LabVIEW | 151210T092621Z | Eumel |
| 027 | dc | 151211T200955Z | SnoringF |
| 051 | Befunge | 151211T141834Z | karhell |
| 456 | Minecraft 15w35a+ | 151210T234649Z | GamrCorp |
| 014 | Vitsy | 151211T112429Z | Addison |
| 511 | ArnoldC | 151210T105058Z | Zycho |
| 054 | Java 7 | 151211T003226Z | corsiKa |
| 049 | Hassium | 151211T000844Z | Jacob Mi |
| 017 | Haskell | 151210T062435Z | nimi |
| 066 | C# | 151210T165202Z | DLeh |
| 030 | PowerShell | 151210T173319Z | AdmBorkB |
| 044 | Fortran | 151210T170246Z | toni |
| 039 | JavaScript ES6 | 151210T095522Z | edc65 |
| 010 | CJam | 151210T031145Z | GamrCorp |
| 034 | JavaScript ES6 | 151210T110022Z | user8165 |
| 022 | R | 151210T104940Z | freekvd |
| 030 | zsh | 151210T101710Z | manatwor |
| 026 | golflua | 151210T100234Z | manatwor |
| 022 | Ruby | 151210T082600Z | Vasu Ada |
| 036 | Mouse | 151210T065245Z | Alex A. |
| 004 | gs2 | 151210T054418Z | Mitch Sc |
| 030 | Python | 151210T033928Z | xnor |
| 014 | Perl 6 | 151210T050755Z | Brad Gil |
| 015 | Mathematica | 151210T035607Z | alephalp |
| 038 | Python 2 | 151210T032216Z | quintopi |
| 016 | Julia | 151210T033659Z | Glen O |
| 015 | Octave | 151210T033008Z | lirtosia |
| 045 | Prolog | 151210T032331Z | Emigna |
| 005 | Pyth | 151210T031355Z | lirtosia |
| 041 | JavaScript ES6 | 151210T030807Z | ETHprodu |
| 007 | Japt | 151210T030133Z | ETHprodu |
| 009 | TIBASIC | 151210T030338Z | lirtosia |
| 052 | Python | 151210T030312Z | Sherlock |
| 004 | Seriously | 151210T030138Z | quintopi |
| 007 | Minkolang 0.14 | 151210T025810Z | El'e |
| 004 | Jolf | 151210T024743Z | Conor O& |
Tcl, 57 bytes
proc P a\ b {while \$a<$b {append s *$a
incr a}
expr 1$s}
proc P {a b p\ 1} {while \$a<$b {set p $p*$a
incr a}
expr $p}
proc P a\ b {while \$a<$b {lappend L $a
incr a}
expr [join $L *]}
proc P {a b p\ 1} {while \$a<$b {set p [expr $p*$a]
incr a}
set p}
☾, 4 characters
⨀´○
Inclusive range. This solution is achieved through the composition of the inclusive range operation and the product operation (I need ´ because ⨀ acts wacky when I don't use it).
SAKO, 56 bytes
PODPROGRAM:F(A,B)
Z=1
*)Z=Z×I
POWTORZ:I=A(1)B
F()=Z
WROC
I took pretty basic approach here, I just iterate from A to B and multiply the values. Unfortunately, every other approach I had thought of had higher byte count.
The result is inclusive.
Full programme, 66 bytes
CZYTAJ:A,B
Z=1
*1)Z=Z×I
POWTORZ:I=A(1)B
DRUKUJ(9,0):Z
STOP1
KONIEC
Itr, 5 bytes
â-º+P
solution for exclusive range
Explantion
â-º+P ; implicit input, stack: [hi low]>
â ; under -> stack: [low hi low]>
- ; subtraction -> stack: [low hi-low]>
º ; zero-based range
+ ; add low to zero based range giving range [low,...hi-1]
P ; product
; implicit output
Itr, 7 bytes
solution for inclusive range
â-1+º+P
2 bytes using the new range built-in
¨P
Pascal, 76 B
Utilizing a recursive definition of the product you may arrive at one of the following solutions:
function p(a,b:integer):integer;begin if a=b then p:=a else p:=a*p(a+1,b)end
function p(a,b:integer):integer;begin if a<b then p:=a*p(a+1,b)else p:=a end
function p(a,b:integer):integer;begin if b>a then p:=a*p(a+1,b)else p:=a end
86 B (standard iterative solution):
Pascal’s for-loop limits are inclusive (just like the \$\prod\$ and \$\sum\$ limits in mathematics are inclusive, too).
In Standard Pascal (as specified by ISO standard 7185) for-loop counters must fulfill certain eligibility criteria (some dialects may be more lenient with that).
Therefore a new variable is declared:
function p(a,b:integer):integer;var i:integer;begin for i:=a+1 to b do a:=a*i;p:=a end
BQN, 7 bytes
×´⊢+↕∘-
Thanks to @ConorO'Brien
BQN, 10 bytes
{×´𝕨+↕𝕩¬𝕨}
Uses an inclusive range. This is the first thing I've ever written in BQN and I couldn't figure out how to make it tacit for the life of me. Any tips appreciated. :)
Thunno 2, 2 bytes
Ip
Attempt This Online! Uses \$[a..b]\$ (the inclusive range).
Explanation: product of the Inclusive range between the two inputs.
HP48 User RPL,
Input is a and b in the stack.
«
'X'
DUP
4 UNROLL
UNROT
1 SEQ
∏LIST
»
05AB1E, 2 bytes
Code:
ŸP
Explanation:
Ÿ # Inclusive range [input, ..., input]
P # Total product of the list
# Implicit printing top of the stack
MATL, 4 bytes
Inclusive Range
2$:p
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.
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
Regex 🐇 (PCRE2 v10.35 or later), 128 bytes
^(?!-x*,(?!-))(-())?+(?=(x*),-?(x*))(?=(x*),?(?=\3)(?=\4)(x*,-?|[^,]*)(x*))\5,?+(?=(\2(xx)*(?11))?)((?*x+)x?+)*(?*x+)(\5\7(,|$))
Takes its input in unary, as two strings of x characters whose lengths represent the numbers, with optional - signs on their left side, joined by a , delimiter, specifying an inclusive range. Returns the absolute value of its output as the number of ways the regex can match. (The rabbit emoji indicates this output method.)
Additionally, capture group \8 is set iff the result is negative. This value is taken from the last found possible match, if there is a conflict. But this regex always returns a consistent value in it within a run.
It takes two shortcuts:
- It assumes that the left argument is less than the right argument. This isn't necessary, and in fact removing this assumption wouldn't cost many bytes.
- If the two arguments have different signs, it doesn't even bother calculating anything, because the result will always be zero. This isn't a necessary shortcut (it worked without it), but it results in a much shorter regex.
^
(?!
-x*,(?!-) # If A is negative and B is nonnegative, let there
# be no possible matches, as the product would be 0.
)
(-())?+ # \2 = set if A is negative
(?=
(x*), # \3 = abs(A);
-?(x*) # \4 = abs(B)
)
(?=
(x*),?(?=\3)(?=\4) # \5 = what to skip so tail = the larger of A or B;
# tail = the larger of A or B
(x*,-?|[^,]*)(x*) # \7 = {the smaller of A or B} - \5
)
\5 # tail = the larger of A or B
,?+ # skip sign of B, if any
# First handle the range from larger inclusive to
# {smaller inclusive or 0 exclusive}
(?=
(\2(xx)*(?11))? # \8 = set iff the inclusive range is negative and has
# an odd number of total members, i.e. the product
# is negative
)
(
(?*x+) # Multiply the number of possibilities by tail.
x?+ # Advance by 1, but if already at the end, allow the
# loop to iterate once more so as to include 0 in
# the count.
)* # Iterate any number of times (cover the whole range)
(?*x+) # Multiply the number of possibilities by tail again
# at the end of the range.
( # Define subroutine (?11)
\5\7 # Clamp the range at the smaller end.
(,|$) # Assert that we've reached the end.
)
As far as I know, this absolutely requires non-atomic lookaround (used here as (?*...) molecular lookahead) and 🐇-output, so it would not be portable to other regex engines currently – though it would be easily portable to 🐇 ECMAScript+(?*).
Nibbles, 2.5 bytes (5 nibbles)
`*>$,
Input is (a,b] (so 5 10 represents the range 6 7 8 9 10).
, # range from 1..(implicit) arg1
> # drop first elements
$ # arg2
`* # product
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
APL, 12 bytes
{⍺×.-1-⍳⍵-⍺}
Explanation on example of arguments 2 and 5:
⍳⍵-⍺ ⍝ Array of numbers from 1 to ⍵-⍺: 1 2 3
1- ⍝ Substract the array from 1: 0 ¯1 ¯2
⍺×.- ⍝ Substract the array from ⍺: 2 3 4
⍝ Then reduce by multiplication, of course
Mathematical justification: ⍺-(1-x) = (⍺-1)+x
Ly, 23 11 bytes
&nRy[p*y,]p
Let's try not doing it the "hard way" this time... :) The code generates a sequence of numbers on a stack, then works through the stack multiplying entries until there's only one number. When the program ends, that single entry prints as a number automatically.
&nRy[p*y,]p -
&n - read in the two numbers
R - generate a range of numbers (inclusive)
y[p y,]p - as long as the stack size is 2 or more
* - multiply the top two entries
K (ngn/k), 11 bytes
{*/x+!y-x}
-1 byte thanks to PyGamer0 for telling me that I don't need ' after +
Another easy one. Exclusive at b.
Explainations:
Assuming that a is 2 and b is 5
{*/x+!y-x} Main program. Takes x as `a` and y as `b`
y-x b-a to fix the range (5 - 2 = 3)
! Range (0 1 2)
x+ += x to each elenent (2 3 4)
*/ Product (2*3*4 = 24)
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.)
Nim, 47 bytes
proc f(a,b,c:var int)=
c=1;for i in a..b:c*=i
All arguments must be variables, passed by reference. Return value in third parameter, original value ignored. As usual with Nim, not very small byte count.
dc, 23 bytes
dsc[lc1+dsc*lclb>g]dsgx
Takes input with the upper bound (inclusive) in register b and the lower bound (inclusive) at the top of the stack. Returns the answer at the top of the stack.
Uses register c a lot, so removing that would save a lot of bytes. Basically it's just a for-loop.
Run as:
{UPPER_BOUND}sb{LOWER_BOUND} dsc[lc1+dsc*lclb>g]dsgx p
Husk, 2 bytes
Π…
# arguments (² => second last argument & ⁰ => last argument) are implicit
… # inclusive numeric range
Π… # product of list
x86-16 machine code, 10 bytes
00000000: 8bc8 f7eb 4b3b d97f f9c3 ....K;....
Listing:
8B C8 MOV CX, AX ; running product start at a
MUL_LOOP:
F7 EB IMUL BX ; multiply running product by b
4B DEC BX ; decrement b
3B D9 CMP BX, CX ; is b > a?
7F F9 JG MUL_LOOP ; if so, go forth and multiply
C3 RET ; return to caller
Input a in AX, b in BX, inclusive of b. Output to AX.
Tests using DOS DEBUG:
Note: before anyone asks... you cannot use LOOPNZ to decrement and compare a and b.
In the case where input a (CX) is 0, it will end the loop before multiplying by the value of a, so no good.
O, 12 bytes
[j:v,;]jv-+*
[j:v Input and save to v without popping
,; Range (1..n inclusive)
]jv- Range end - start
+ Add it vectorised with range
* Product
Branch, 26 bytes
Z}N\;^-[n^\z^*Zn}N^\o^-]z#
Try it on the online Branch interpreter!
Z Save the value (the first argument) as register Z
}N Increment and save to N
\; Go to the right child and copy the parent value
^- Go to the parent and subtract (the left child is pre-set as the second argument)
[ ] While non-zero (basically, while N is not the same as the end)
n Restore register N
^\z^ Put Z in the right child and go to the parent
*Z Multiply and save to Z; these three lines do Z = Z * N
n}N Restore N, increment, and save back to N
^\o^- Compare against register O; automatically set to the second argument
z# Restore Z, the product, and output
This is right-exclusive.
Factor + math.unicode, 12 bytes
[ [a,b] Π ]
It's a quotation (anonymous function) that takes 2 integers from the data stack as input and leaves one integer on the data stack as output.
[a,b]Create a range from two integers. As you may have guessed, this is inclusive of both. All of the other words are also available, such as[a,b).ΠFind the product.
R, 21 bytes
Thanks to Dominic van Essen for helping me brainstorm input methods.
prod((a=scan()):a[2])
Uses inclusive range. Try it online!
Explanation
a=scan() Read the two inputs as a vector and assign it to a
( ): Use a as the lower end of a range (R interprets this as "use the
first element of the vector" by default)
a[2] Use the second element of a as the upper end of the range
prod( ) Take the product of all numbers in the range
Scala, 9 bytes
_.product
Accepts input as a Range object (inclusive or exclusive).
Arn, 5 bytes
ë|¶Ý║
Explained
Unpacked: *\(=>\
\ Fold with
* Multiplication
( Begin expression
\ Fold with
=> Inclusive range
_ Variable initialized to STDIN; implied
) End expression; implied
The power of the fold operator, alternatives would be *\=>?1 or *\=>:} (hypothetically, for some reason they are broken as of typing this. Trying to fix).
Charcoal, 20 bytes
≔¹ξNαNβF…αβ«≔×ξιξ»Iξ
Verbose
Assign 1 x
InputNumber a; InputNumber b;
for(Range a b){
Assign (Times x i) x
}
Print Cast x
Javascript
f=(a,b)=>a>b||a*f(a+1,b)
or
f=(a,b)=>[...Array(b-a).keys()].map(i=>i+a).reduce((a,b)=>a*b)
Python
f=lambda a,b:reduce(lambda x,y:x*y,range(a,b))
Kotlin, 30 bytes
Range is inclusive
{a,b->(a..b).reduce{c,d->c*d}}
Kotlin, 21 bytes
If you can take input as an IntRange:
{it.reduce{c,d->c*d}}
Gol><>, 13 bytes
I::I-F$M:@*|h
Takes b then a from stdin, and uses inclusive range.
How it works
I::I-F$M:@*|h
I::I- Take b, duplicate twice, take a, subtract
[b b b-a]
F | Repeat b-a times:
[counter product]
$M Swap two, decrement counter
[product counter-1]
:@ Duplicate, rotate 3
[counter-1 counter-1 product]
* Multiply
[counter-1 product']
h Print top as number and exit
W, 3 bytes (inclusive)
.*r
Explanation
ab. % Generate inclusive range from a to b
* % Multiplication
r % Preserve the operation's action & reduce by it
Keg -hr, 3 bytes
ɧ∑*
Explanation:
ɧ # Generate inclusive range from two integer inputs
∑* # Calculate product of whole stack
# Output
GolfScript, 8 bytes
Idea copied from the gs2 solution.
~,\>{*}*
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
APL (Dyalog Extended), 8 3 bytesSBCS
×/…
… range
×/ multiplication across
This is an "atop" so a(×/…)b is ×/a…b.
Triangular, 21 20 bytes
$\S=t$iUprP%..%/*U:<
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:<
Brachylog, 3 bytes
⟦₃×
Input is passed as [A,B]. The range is exclusive of B, but could be made inclusive by replacing the ₃ with ₂.
JavaScript (ES6), 25 bytes
f=(a,b)=>a-b?a*f(a+1,b):b
Inclusive.
Clam, 5 bytes
p;Brr
Explanation
p - Print...
; - Product of...
B - Range...
r - Next input
r - Next input
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
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:
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
Pushy, 8 bytes
Non-competing as the language postdates the challenge.
w-:&h;P#
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.
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).
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.
C#, 56 Bytes
int f(int a,int b){var r=1;for(;a<b;a++)r*=a;return r;}
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
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)
Perl 6 - 15 bytes
{[*] $^a..$^b}
Usage:
> {[*] $^a..$^b}(2,5)
120
Swift, 26 58 bytes
func p(a:Int,b:Int)->Int{return(a+1..<b).reduce(a){$0*$1}}
><>, 33 bytes
1&:@$:@)?\&n;
:$@:+1&*&:/?@@$@)@
My first fish attempt.
Inclusive range
Assumes a and b are on the stack.
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)
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)))
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
)
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.
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
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
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 ]
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.
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. 1¶ 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.
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].)
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))
Detour, 3 bytes (non-competing)
rP.
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.
𝔼𝕊𝕄𝕚𝕟, 4 chars / 11 bytes
⨴⩥…ï
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.)
Python 56
a=input()
b=input()
print reduce(int.__mul__,range(a,b))
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
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!
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.
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;}
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)
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
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.
TI-Basic, 14 11 bytes
Prompt A,B:prod(randIntNoRep(A,B
LabVIEW, 14 LabVIEW Primitives
Range is exclusive. Creates an array from a to b then multiplies all elements.
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
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.
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
Download the world here.
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:
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
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
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
Haskell, 19 17 bytes
a#b=product[a..b]
Usage example: 2#5-> 120.
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);
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.
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
JavaScript (ES6), 39
Inclusive range.
(a,b)=>[...Array(b-a)].map(_=>b*=a++)|b
Note: map beats reduce once again
CJam, 6 19 18 10 bytes
Thanks to Dennis and RetoKoradi for help with golfing!
q~1$-,f+:*
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~,>:*
Takes input as a b. Calculates PI [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.
R, 22 bytes
function(a,b)prod(a:b)
zsh, 30 bytes
f=({$1..$2})
echo $[${f// /*}]
Sample run:
manatwork% zsh product.zsh 5 10
151200
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
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
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
$
gs2, 4 bytes
Hex: 57 0e 4f 65
Mnemonics: read-nums dump crange product
dump pops a list from the stack and pushes its contents (like ~ in GolfScript), and crange gives [a,b).
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).
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 ..
Mathematica, 15 bytes
1##&@@Range@##&
A shorter solution that only works for non-negative integers:
#2!/(#-1)!&
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.
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.
Octave, 15 bytes
@(a,b)prod(a:b)
Straightforward. Uses the inclusive range.
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
Pyth, 5 bytes
*FrQE
Pyth doesn't have product, so we reduce * over the range.
Uses exclusive range.
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.
Japt, 7 bytes
Easy challenges like this are always fun. :)
UoV r*1
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...
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
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
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
Minkolang 0.14, 7 bytes
nnL$*N.
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.






