| Bytes | Lang | Time | Link |
|---|---|---|---|
| 061 | AWK | 250825T132621Z | xrs |
| 052 | Google Sheets | 240101T082959Z | z.. |
| 061 | Perl 5 a | 240101T070031Z | Xcali |
| 057 | Scala | 240101T004602Z | 138 Aspe |
| 087 | Swift | 231001T172451Z | macOSist |
| 069 | JavaScript Node.js | 230113T152055Z | l4m2 |
| 034 | jq | 231225T031510Z | manatwor |
| 029 | Kamilalisp | 231001T173343Z | Kamila S |
| 005 | Thunno 2 | 230719T142842Z | The Thon |
| 009 | Brachylog | 230117T172637Z | DLosc |
| 005 | Jelly | 230117T081659Z | Unrelate |
| 007 | Japt | 170523T094700Z | Shaggy |
| 007 | Vyxal | 230114T232928Z | pacman25 |
| 052 | Arturo | 230114T200150Z | chunes |
| nan | 230114T111244Z | The Thon | |
| 007 | Pyt | 230113T131845Z | Kip the |
| 006 | Husk | 211229T195826Z | Natte |
| 043 | Factor + math.matrices | 211229T190823Z | chunes |
| 057 | Python 3 | 170523T092342Z | ceruleus |
| 006 | Jelly | 170329T233823Z | user6213 |
| 041 | Shell + common utilities | 151128T213948Z | Digital |
| 3540 | TeaScript | 151128T154810Z | ETHprodu |
| 048 | Ruby | 151128T152116Z | Vasu Ada |
| 094 | Prolog SWI | 151130T135423Z | Emigna |
| 022 | Candy | 151129T084006Z | Dale Joh |
| 070 | PHP | 151130T123710Z | Martijn |
| 011 | Pyth | 151129T230603Z | TanMath |
| 070 | Kotlin | 151129T184824Z | succcubb |
| 086 | JAVA 86 Bytes | 151129T144211Z | Yassin H |
| 083 | Perl 5 | 151129T105151Z | Dale Joh |
| 067 | Perl 5 | 151129T070731Z | msh210 |
| 051 | Haskell | 151129T061740Z | xnor |
| 020 | J | 151129T000721Z | lirtosia |
| 016 | APL | 151128T061500Z | Alex A. |
| 054 | Haskell | 151128T125502Z | nimi |
| 008 | Pyth | 151128T083712Z | orlp |
| 102 | Python | 151128T065125Z | TanMath |
| 091 | Perl 5 | 151128T191410Z | Walter A |
| 086 | JavaScript ES6 | 151128T190245Z | nicael |
| 027 | Perl 6 | 151128T164110Z | Brad Gil |
| 012 | CJam | 151128T070758Z | Reto Kor |
| nan | 151128T161857Z | Doorknob | |
| 090 | JavaScript ES6 | 151128T154924Z | user8165 |
| 024 | MATLAB | 151128T091230Z | Stewie G |
| 096 | C | 151128T082711Z | xsot |
| 051 | Python 2 | 151128T061132Z | xsot |
| 017 | K | 151128T064803Z | JohnE |
| 039 | R | 151128T060239Z | Alex A. |
| 024 | Julia | 151128T062749Z | Alex A. |
| 025 | Mathematica | 151128T063321Z | alephalp |
| 018 | Minkolang 0.14 | 151128T053504Z | El'e |
| 022 | Octave | 151128T062107Z | alephalp |
| 010 | Pyth | 151128T054108Z | FryAmThe |
Google Sheets, 52 bytes
=SORT(UNIQUE(TOCOL(MAKEARRAY(N,N,LAMBDA(i,j,i*j)))))
Scala, 57 bytes
Golfed version. Attempt This Online!
n=>(1 to n).flatMap(i=>(1 to n).map(i*_)).distinct.sorted
Ungolfed version. Attempt This Online!
def f(n: Int): Array[Int] = {
// Construct a Range from 1 to the input
val x = 1 to n
// Compute the outer product of x with itself
val o = for {
i <- x
j <- x
} yield i * j
// Get the unique elements and sort them
o.distinct.sorted.toArray
}
Swift, 146 137 133 87 bytes
var t={n in Set((1...n).map{i in(1...n).map{(i,$0)}}.joined().map{$0.0*$0.1}).sorted()}
To run, paste this into a playground or the REPL and call t(_:).
Here's an expanded version:
func table(n: Int) -> [[Int]] {
let range = 1...n
let combos = range.map { i in
range.map { j in
(i, j)
}
}.joined()
let products = combos.map { combo in
combo.0 * combo.1
}
let uniques = Set(products)
let sorted = uniques.sorted()
return sorted
}
Let's run through this step by step. We'll assume that n is 4.
First, we create a closed range containing all the numbers from 1 to n, inclusive. So, range is set to 1...4. (In the golfed version, it's more efficient to just create the range twice.)
Now we map over range twice, one map inside the other. This effectively creates a nested array containing every permutation of two numbers within the range 1...n. We then join these arrays to remove the nesting. For our example, this sets combos to
[
(1, 1), (1, 2), (1, 3), (1, 4),
(2, 1), (2, 2), (2, 3), (2, 4),
(3, 1), (3, 2), (3, 3), (3, 4),
(4, 1), (4, 2), (4, 3), (4, 4)
]
(In actuality, it's a FlattenSequence instead of an Array, but that doesn't matter for what we're going to do with it.)
Next, we map over combos, returning the results of multiplying each tuple's elements together. (Using tuples instead of more arrays saves 2 bytes due to the shorter element access syntax.) This sets products to
[
1, 2, 3, 4,
2, 4, 6, 8,
3, 6, 9, 12,
4, 8, 12, 16
]
We then create a Set from this array. Sets are unordered, and can only contain one of each item. This enables us to concisely remove duplicate products, at the cost of losing the order of the products. For all intents and purposes, this sets uniques to
[1, 2, 3, 4, 6, 8, 9, 12, 16].shuffled()
Finally, we call sorted() on uniques to get our ordering back, and return the result, which is
[1, 2, 3, 4, 6, 8, 9, 12, 16]
By default, sorted() does the same thing as sorted(by: <), which sorts in increasing order.
JavaScript (Node.js), 69 bytes
n=>[...a=Array(i=n*n)].map(x=>a[q=~(--i%n)*~(i/n)]=q)&&a.filter(x=>x)
JavaScript (Node.js), 76 bytes
n=>[...Array(n*n)].flatMap((_,i,x)=>x.every((_,j)=>~(j/n)*~(j%n)+~i)?[]:i+1)
No recursion like other answers
jq, 34 characters
[range(1;.+1)*range(1;.+1)]|unique
Sample run:
bash-5.2$ jq --compact-output '[range(1;.+1)*range(1;.+1)]|unique' <<< 5
[1,2,3,4,5,6,8,9,10,12,15,16,20,25]
(range() not generates array — “The numbers are produced as separate outputs.” Found no way to multiply a range's output by itself.)
Thunno 2, 5 bytes
Ṗ€pUṠ
Explanation
Ṗ€pUṠ # Implicit input
Ṗ # Cartesian product
€p # Product of each
U # Uniquify the list
Ṡ # And sort it
# Implicit output
Brachylog, 9 bytes
⟦₁⟨∋×∋⟩ᵘo
Explanation
⟦₁⟨∋×∋⟩ᵘo
⟦₁ Range from 1 to input number, inclusive
ᵘ Get all unique outputs of this predicate:
∋ Pick a number from that range
∋ Pick another number from that range
⟨ × ⟩ Multiply them together
o Sort the resulting list
Jelly, 5 bytes
Ṭẋ)ST
) For each x in 1 .. n:
Ṭ Create a list containing 1 at index x and 0s before it,
ẋ and repeat it x times.
S Sum the results element-wise,
T and yield the indices of non-zeros in the result.
Japt, 13 12 11 13 11 8 7 bytes
õ ï* Íâ
õ ï* Íâ :Implicit input of integer U
õ :Range [1,U]
ï :Cartesian product with itself
* :Reduce each pair by multiplication
Í :Sort
â :Deduplicate
Thunno, \$ 12 \log_{256}(96) \approx \$ 9.88 bytes
R1+DZ!.PZU
Explanation
R1+DZ!.PZUz: # Implicit input Example (n=5)
R1+ # [1..input] [1, 2, 3, 4, 5]
DZ! # Cartesian product with itself [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]]
.P # Product of each inner list [1, 2, 3, 4, 5, 2, 4, 6, 8, 10, 3, 6, 9, 12, 15, 4, 8, 12, 16, 20, 5, 10, 15, 20, 25]
ZU # Uniquified [1, 2, 3, 4, 5, 6, 8, 10, 9, 12, 15, 16, 20, 25]
z: # And sorted [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 20, 25]
# Implicit output
Screenshot
Pyt, 7 bytes
řĐɐ*ƑỤş
ř implicit input (n); push [1,2,...,n]
Đ duplicate
ɐ* generate multiplication table
Ƒ flatten array
Ụ get unique elements
ş sort in ascending order; implicit print
Factor + math.matrices, 43 bytes
[ [1,b] dup outer [ ] gather natural-sort ]
Explanation
! 3
[1,b] ! { 1 2 3 }
dup ! { 1 2 3 } { 1 2 3 }
outer ! { { 1 2 3 } { 2 4 6 } { 3 6 9 } }
[ ] gather ! { 1 2 3 4 6 9 }
natural-sort ! { 1 2 3 4 6 9 }
Python 3, 57 bytes
r=range(1,n+1);print(sorted({i*j for i in r for j in r}))
Jelly, 6 bytes, language postdates challenge
×þµFṢQ
There are so many different ways to do this in 6 bytes that it feels like 5 might be possible. I haven't found a way, though.
Explanation
×þµFṢQ
×þ Form multiplication (×) table (þ) up to the input
µ Fix a parsing ambiguity (µ in Jelly is like parentheses in C)
F Flatten the table into a single continuous list
Ṣ Sort the elements of the list
Q Take the unique elements of the sorted list
Shell + common utilities, 41
seq -f"seq -f%g*%%g $1" $1|sh|bc|sort -nu
Or alternatively:
Bash + coreutils, 48
eval printf '%s\\n' \$[{1..$1}*{1..$1}]|sort -nu
Constructs a brace expansion inside an arithmetic expansion:
\$[{1..n}*{1..n}] expands to the arithmetic expansions $[1*1] $[1*2] ... $[1*n] ... $[n*n] which are evaluated and passed to printf, which prints one per line, which is piped to sort.
Careful use of quotes, escapes and eval ensure the expansions happen in the required order.
Or alternatively:
Pure Bash, 60
eval a=($(eval echo [\$[{1..$1}*{1..$1}\]]=1))
echo ${!a[@]}
TeaScript, 37 35 chars; 40 bytes
Saved 2 bytes thanks to @Downgoat
TeaScript is JavaScript for golfing.
(b+r(1,+x¬)ßam(z=>z*l±s`,`.u¡s»l-i)
Ungolfed and explanation
(b+r(1,+x+1)m(#am(z=>z*l)))s(',').u()s(#l-i)
// Implicit: x = input number
r(1,+x+1) // Generate a range of integers from 1 to x.
m(# // Map each item "l" in this range "a" to:
am(z=> // a, with each item "z" mapped to
z*l)) // z * l.
(b+ ) // Parse this as a string by adding it to an empty string.
s(',') // Split the string at commas, flattening the list.
.u() // Take only the unique items from the result.
s(#l-i) // Sort by subtraction; the default sort sorts 10, 12, 100, etc. before 2.
// Implicit: output last expression
Ruby, 50 48 bytes
->n{c=*r=1..n;r.map{|i|c|=r.map{|j|i*j}};c.sort}
Ungolfed:
->n {
c=*r=1..n
r.map { |i| c|=r.map{|j|i*j} }
c.sort
}
Using nested loop to multiply each number with every other number upto n and then sorting the array.
50 bytes
->n{r=1..n;r.flat_map{|i|r.map{|j|i*j}}.uniq.sort}
Usage:
->n{c=*r=1..n;r.map{|i|c|=r.map{|j|i*j}};c.sort}[4]
=> [1, 2, 3, 4, 6, 8, 9, 12, 16]
Prolog (SWI), 94 bytes
As the output only had to be in a reasonable format I've chosen to save 7 bytes by returning the list (which displays it), rather than doing an explicit write.
Code:
p(N,S):-findall(O,between(1,N,O),M),findall(Z,(member(X,M),member(Y,M),Z is X*Y),L),sort(L,S).
Explained:
p(N,S):-findall(O,between(1,N,O),M), % Get a list of numbers between 1 and N.
findall(Z,(member(X,M),member(Y,M),Z is X*Y),L), % Create a list of the products of the different combinations of elements in the list of numbers between 1 and N.
sort(L,S). % Sort and remove doubles
Example:
p(6,L).
L = [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30, 36]
Try it out online here
Candy, 22 bytes
Input on stack
R0C(*=bA)bo(~Xe{|A?}x)
Long form:
range1
digit0
cart # cartesian product of range0 and itself
while
mult
popA
stack2
pushA # push products to second stack
endwhile
stack2
order
while # loop to dedup
peekA
pushX
equal
if
else
pushA
println
endif
XGetsA
endwhile
PHP, 74,73 70bytes
while($i++<$j=$n)while($j)$a[]=$i*$j--;$a=array_unique($a);sort($a);
print_r($a); // Not counted, but to verify the result
Ungolfed:
while($i++<$j=$n)
while($j)
$a[]=$i*$j--;
Previous:
while(($j=$i++)<$n)for(;$j++<$n;)$a[]=$i*$j;$a=array_unique($a);sort($a);
Not 100% sure what to do with output, but $a contains an array with the corresponding numbers. $n is the number geven via $_GET['n'], with register_globals=1
Pyth, 11 bytes
S{sm*RdSdSQ
This is similar to the Julia answer. Thanks to @Maltysen
Kotlin, 70 bytes
val a={i:Int->(1..i).flatMap{(1..i).map{j->it*j}}.distinct().sorted()}
Ungolfed version:
val a: (Int) -> List<Int> = {
i -> (1..i).flatMap{ j -> (1..i).map{ k -> j * k } }.distinct().sorted()
}
Test it with:
fun main(args: Array<String>) {
for(i in 1..12) {
println(a(i))
}
}
JAVA - 86 Bytes
Set a(int a){Set s=new TreeSet();for(;a>0;a--)for(int b=a;b>0;)s.add(a*b--);return s;}
Ungolfed
Set a(int a){
Set s = new TreeSet();
for (;a>0;a--){
for(int b = a;b>0;){
s.add(a*b--);
}
}
return s;
}
Perl 5, 83 bytes
Here's a perl version that doesn't do a sort, and doesn't require duplicate removal. I'd like to claim that makes it faster, but it's running time is actually O(n^2.5)
$n=pop;for$i(1..$n*$n){for$j(1+int(($i-1)/$n)..sqrt($i)){if($i%$j==0){say$i;last}}}
A one-character longer and much slower version of this same approach reads as follows:
$n=pop;
for $i (1..$n*$n) {
for $j (1..$i) {
if ($i%$j == 0 && $i <= $n*$j && $i >=$ j*$j) {
say $i;
last
}
}
}
It works by traversing the multiplication table in a strictly ordered fashion.
Perl 5, 67 bytes
for$i(1..($n=pop)){$a{$_*$i}++for 1..$n}map say,sort{$a<=>$b}keys%a
Haskell, 51 bytes
f n=[i|i<-[1..n*n],elem i[a*b|a<-[1..n],b<-[1..n]]]
Pretty boring. Just filters the list [1..n*n] to the elements of the form a*b with a and b in [1..n]. Using filter gives the same length
f n=filter(`elem`[a*b|a<-[1..n],b<-[1..n]])[1..n*n]
I tried for a while to generate the list of products with something more clever like concatMap or mapM, but only got longer results. A more sophisticated check of membership came in at 52 bytes, 1 byte longer, but can perhaps be shortened.
f n=[k|k<-[1..n*n],any(\a->k`mod`a<1&&k<=n*a)[1..n]]
J, 21 20 bytes
Thanks to @Zgarb for -1 byte!
/:~@~.@,@(1*/~@:+i.)
My first J answer! Golfing tips are appreciated, if there is something to golf.
This is a monadic function; we take the outer product by multiplication of the list 1..input with itself, flatten, take unique elements, and sort.
APL, 18 16 bytes
{y[⍋y←∪,∘.×⍨⍳⍵]}
This is an unnamed monadic function. The output is in ascending order.
Explanation:
⍳⍵]} ⍝ Get the integers from 1 to the input
∘.×⍨ ⍝ Compute the outer product of this with itself
, ⍝ Flatten into an array
∪ ⍝ Select unique elements
y← ⍝ Assign to y
{y[⍋ ⍝ Sort ascending
Fixed an issue and saved 2 bytes thanks to Thomas Kwa!
Haskell, 55 54 bytes
import Data.List
f n=sort$nub[x*y|x<-[1..n],y<-[1..x]]
Usage example: f 4 -> [1,2,3,4,6,8,9,12,16].
nub removes duplicate elements from a list.
Edit: @Zgarb found a superfluous $.
Pyth, 8 bytes
S{*M^SQ2
Explanation: SQ takes the evaluated list input (Q) and makes a list [1, 2, ..., Q]. ^SQ2 takes the Cartesian product of that list with itself - all possible product combinations. *M multiplies all these pairs together to form all possible results in the multiplication table and S{ makes it unique and sorts it.
Python, 124 102 bytes
n=input()
l=[1]
for i in range(1,n+1):
for j in range(1,n+1):l.append(i*j)
print sorted(list(set(l)))
More pythonic!
Perl 5, 91 bytes
for my $y (1 .. $ARGV[0]){
map {$s{$n}++ unless($s{$n=$y*$_}) } ($y .. $ARGV[0])
}
print join(" ", sort {$a<=>$b} keys %s) . "\n";
to be run by passing the argument on the command line. It is quite a few declarations short of running with strictures and warnings.
JavaScript (ES6), 86 bytes
n=>{n++;a=[];for(j=1;j<n;j++)for(i=1;i<n;i++)if(a.indexOf(i*j)<0)a.push(i*j);return a}
Looking to shorten it (maybe will try nesting loops).
Perl 6, 27 bytes
{squish sort 1..$_ X*1..$_} # 27
{unique sort 1..$_ X*1..$_} # 27
{sort unique 1..$_ X*1..$_} # 27
Example usage:
say {squish sort 1..$_ X*1..$_}(3); # (1 2 3 4 6 9)
my $code = {squish sort 1..$_ X*1..$_}
for 1..100 -> \N { say $code(N) }
my &code = $code;
say code 4; # (1 2 3 4 6 8 9 12 16)
CJam, 14 12 bytes
Latest version with improvements proposed by @aditsu:
{)2m*::*0^$}
This is an anonymous function. Try it online, with input/output code needed for testing it.
@Martin proposed another very elegant solution ({,:)_ff*:|$}) with the same length. I used the one by aditsu because it was much more similar to my original solution.
The main difference to my original solution is that this keeps the 0 value in the original sequence, which saves 2 bytes at the start. You'd think that this would not help, because you have to remove the 0 value from the result. But the core of @aditsu's idea is the 0^ at the end, which is a set difference with 0. This removes the 0, and at the same time, since it's a set operation, eliminates duplicate elements from the solution set. Since I already needed 2 bytes to eliminate the duplicates before, removing the 0 is then essentially free.
Explanation:
{ Start anonymous function.
) Increment to get N+1.
2m* Cartesian power, to get all pairs of numbers in range [0, N].
::* Reduce all pairs with multiplication.
0^ Remove 0, and remove duplicates at the same time since this is a set operation.
$ Sort the list.
} End anonymous function.
zsh, 86 56 bytes
thanks to @Dennis for saving 30(!) bytes
(for a in {1..$1};for b in {1..$1};echo $[a*b])|sort -nu
Explanation / ungolfed:
( # begin subshell
for a in {1..$1} # loop through every pair of multiplicands
for b in {1..$1}
echo $[a*b] # calculate a * b, output to stdout
) | sort -nu # pipe output of subshell to `sort -nu', sorting
# numerically (-n) and removing duplicates (-u for uniq)
This doesn't work in Bash because Bash doesn't expand {1..$1}—it just interprets it literally (so, a=5; echo {1..$a} outputs {1..5} instead of 1 2 3 4 5).
JavaScript (ES6), 92 90 bytes
n=>eval(`for(r=[],a=n;a;a--)for(b=n;b;)~r.indexOf(x=a*b--)||r.push(x);r.sort((a,b)=>a-b)`)
Explanation
n=>eval(` // use eval to remove need for return keyword
for(r=[],a=n;a;a--) // iterate for each number a
for(b=n;b;) // iterate for each number b
~r.indexOf(x=a*b--) // check if it is already in the list, x = value
||r.push(x); // add the result
r.sort((a,b)=>a-b) // sort the results by ascending value
// implicit: return r
`)
Test
N = <input type="number" oninput="result.innerHTML=(
n=>eval(`for(r=[],a=n;a;a--)for(b=n;b;)~r.indexOf(x=a*b--)||r.push(x);r.sort((a,b)=>a-b)`)
)(+this.value)" /><pre id="result"></pre>
MATLAB, 24 bytes
@(n)unique((1:n)'*(1:n))
C, 96 bytes
i,a[1<<16];main(n){for(scanf("%d",&n);i<n*n;a[~(i%n)*~(i++/n)]="%d ");while(i)printf(a[i--],i);}
This prints the numbers in descending order. Suggestions are welcomed as this looks far from optimal.
Python 2, 61 51 bytes
lambda n:sorted({~(i%n)*~(i/n)for i in range(n*n)})
Thanks to xnor for shortening some syntax.
K, 17 bytes
t@<t:?,/t*\:t:1+!
Not much to say here. Sort (t@<t:) the unique items (?) of the flattened (,/) multiplied cartesian self-product (t*\:t:) of 1 up to and including N (1+!).
In action:
t@<t:?,/t*\:t:1+!5
1 2 3 4 5 6 8 9 10 12 15 16 20 25
R, 39 bytes
cat(unique(sort(outer(n<-1:scan(),n))))
This reads an integer from STDIN and writes a space delimited list to STDOUT.
We create the multiplication table as a matrix using outer, implicitly flatten into a vector and sort using sort, select unique elements using unique, and print space delimited using cat.
Julia, 24 bytes
n->sort(∪((x=1:n)*x'))
This is an anonymous function that accepts an integer and returns an integer array.
Ungolfed:
function f(n::Integer)
# Construct a UnitRange from 1 to the input
x = 1:n
# Compute the outer product of x with itself
o = x * transpose(x)
# Get the unique elements, implicitly flattening
# columnwise into an array
u = unique(o)
# Return the sorted output
return sort(u)
end
Mathematica, 25 bytes
Union@@Array[1##&,{#,#}]&
Minkolang 0.14, 25 22 18 bytes
I remembered that I very conveniently implemented Cartesian products before this question was posted!
1nLI20P[x*1R]sS$N.
Try it here. (Outputs in reverse order.)
Explanation
1 Push a 1 onto the stack
n Take number from input (n)
L Pushes 1,2,...,n onto the stack
I Pushes length of stack so 0P knows how many items to pop
2 Pushes 2 (the number of repeats)
0P Essentially does itertools.product(range(1,n+1), 2)
[ Open for loop that repeats n^2 times (0P puts this on the stack)
x Dump (I know each product has exactly two numbers
* Multiply
1R Rotate 1 step to the right
] Close for loop
s Sort
S Remove duplicates ("set")
$N. Output whole stack as numbers and stop.
Octave, 22 bytes
@(n)unique((a=1:n)'*a)
