title: Find the powertrain!

text:
# Question
Title: Find the powertrain!
## The winner (pretty obviously) is Dennis ♦, who used Jelly with 10 bytes!

This challenge will still be up here, however results won't be taken anymore.

---

The powertrain of a number is a concept by John Conway (who is also notable for making Conway's Game of Life, but that's not the point). It is defined as so:

For any number ..., the powertrain of the number is ... (i.e. every 2nd digit, from left to right, is a power of the digit before that). This process is repeated until the result is a single digit.

EXAMPLES:

`2592 => (2^5)(9^2) = 2592 <= Cannot be further decomposed
 135 => (1^3)5 = 5
 1234 => (1^2)(3^4) = 81 => (8^1) = 8
 1100 => (1^1)(0^0) = 1 # (0^0) = 1
 -42 => -42 # Negative numbers output the input`

Your challenge is, for any number `n` in the input, return `powertrain(n)` (i.e. `n` after the powertrain decomposition is finished) as output.

This is code golf, so shortest amount of bytes wins.

DISCLAIMER-THINGS:

* You can have an odd number of digits in the input, the last digit just won't have a power.
* 0^0 is 1, because if it was 0, then a lot of numbers would instantly collapse to 0 or 1.
* If the number is indestructible in any part of the computation process (e.g. if it ends up with `2592`), then you can just output the number.
* If the input is `< 10` (i.e. all single digit numbers and negatives), output the input.

I'll probably announce a winner after a few hours days.

Current leaderboard:

> 1. Jelly (Dennis ♦): 10
> 2. Pyth (DenkerAffe): 16
> 3. MATL (Don Muesli): 21
> 4. Perl (Ton Hospel): 42
> 5. Haskell (Damien): 64
> 6. Javascript ES6 (edc65): 71
> 7. Mathematica (murphy): 74
> 8. Mathematica (LegionMammal978) and Haskell (Renzeee): 77
> 9. Python 2 (mathmandan): 111
> 10. Python 3 (Erwan): 161
> 11. Java 8 (Blue): 229
> 12. Oracle SQL 11.2 (Jeto): 456
> 13. Befunge '93 (Lex): 490

# Answer
> 4 votes
# Jelly, ~~15~~ ~~14~~ ~~12~~ 10 bytes

```
Ds2*/€Pµ³¡

```

Try it online!

### How it works

```
Ds2*/€Pµ³¡  Main link. Argument: n

D           Convert n into the array of its decimal digits.
 s2         Split into pairs of digits.
   */€      Reduce each pair by exponentiation.
      P     Take the product of the resulting powers.
       µ    Push the preceding chain as a link, and start a new one.
        ³¡  Execute the link n times and return the last result.

```

# Answer
> 5 votes
# Haskell, ~~67~~ 64 bytes

**(\>\>=(==))\>\>=until$p.show** is an unnamed function taking an integer as input and returning its powertrain.

Saved 3 bytes thanks to Zgarb

```
p(x:y:r)=p[x]^p[y]*p r;p[]=1;p x=read x
(>>=(==))>>=until$p.show

```

# Answer
> 4 votes
# Perl, 42 ~~48~~ bytes

Include +2 for `-lp` (you can drop the `-l` too but I like newlines)

Run with input on STDIN, e.g.

```
perl -lp powertrain.pl <<< 1234

```

`powertrain.pl`:

```
s/\B/1&pos?"**":"*"/eg until++$.>($_=eval)

```

(on older perls you can also drop the space between the regex and until)

This won't be able to handle the fixed point `24547284284866560000000000` but that large a value won't work anyways because by that time perl switched to exponential notation.

The above version is will in fact work fast (at most `2592` loops) for all numbers that perl can represent without using exponential notation since it is proven that there are no fixed points between `2592` and `24547284284866560000000000` (https://oeis.org/A135385)

This does however assume something as yet unproven. In principle there could be a reduction that takes more than `X=10^7` steps (it is conjectured that no non-fixed point takes more than 16 steps, https://oeis.org/A133503) whose value dips below `X` (but above `10^7`) and then goes up again. If that is the case I must fall back to:

```
s/\B/1&pos?"**":"*"/eg until$s{$_=eval}++||/-/

```

## Explanation

The code works by putting `**` and `*` (alternating) between the digits

```
s/\B/1&pos?"**":"*"/eg

```

so `2592` becomes `2**5*9**2` and `12345` becomes `1**2*3**4*5`. These are valid perl expressions that can be evaluated with

```
$_ = eval

```

(`0**0` is `1` in perl). Then just put a loop around that with a counter that makes it expire. Since except for the fixed points the values go down extremely quickly the powertrain series converges before the counter gets a chance to really get going

# Answer
> 3 votes
# Pyth, ~~25~~ ~~18~~ ~~11~~ 16 bytes

```
?<Q0Qu*F^McjGT2Q

```

Try it here!

~~7~~ 14 bytes saved with help from @Jakube

## Explanation

```
?<Q0Qu*F^McjGT2Q   # Q = eval(input)

?<Q0Q              # If input is negative return Q
     u         Q   # apply the following function until we reach a cycle
                   # starting value is Q and the current value is in G
           jGT     # split input into a list of digits
          c   2    # split into pairs of 2
        ^M         # compute the power for every pair
      *F           # compute the product of all powers

```

# Answer
> 3 votes
# Python 2, 111 bytes

```
def p(n,b=0,o=''):
 if n<1:return n
 for c in str(n):o+=c+'**'[b:];b=~b
 j=eval(o+'1');return p(j)if j-n else j

```

The idea is to make a string where the digits of `n` are separated by operations which alternate between `*` and `**`, and then `eval` that string. (Other solutions use this same idea; see for example Ton Hospel's Perl answer.)

So, the operation switches back and forth between `'**'[0:]`, which is `**`, and `'**'[-1:]`, which is just `*`.

However, by the end of the `for`-loop, the string ends with an operation (one or the other), so we either need to drop the last operation, or else add another digit, in order for the string to make sense.

Fortunately, appending a `1` on the end will work no matter which operation is last. (If you like, `1` is a one-sided identity from the right, for both multiplication and exponentiation. Another way of saying this is that `powertrain(n) == powertrain(10*n + 1)` for all `n>0`.)

Finally, if the result of the `eval` happens to be the same as the input (as in a length-`1` cycle), the function terminates. Otherwise, the function calls itself on the result. (It will hang forever on any cycle of length `> 1`, but according to the OP's comments I am allowed to assume there are no such cycles.)

(Note: the above explanation works for single-digit positive integers, since a single-digit input `n` will be completed to `n**1` which will result in a `1`-cycle. However, we also need to accept non-positive input, so there's a condition at the beginning that short-circuits if the input is less than `1`. We could eliminate that line, and save 17 bytes, if the input were guaranteed to be non-negative.)

# Answer
> 3 votes
## Java 8, ~~265~~ ~~244~~ 229 bytes

This is my first answer, but I have been reading this site for a while and think I know what I'm doing. At least it beats befunge and SQL...

Unfortunately, like other answers, this one does not work for 24547284284866560000000000 due to java'a built in restrictions on how large integers can get.

Saved 36 bytes thanks to @JackAmmo

```
public int p(int n){if(n<10)return n;int i=1,t=1,s=(int)Math.log10(n)+1,r[]=new int[s];for(;i<=s;){int a=(int)Math.pow(10,i);r[s-i++]=n%a/(a/10);}for(i=0;i<s-1;i++)t*=Math.pow(r[i],r[++i]);if(s%2==1)t*=r[s-1];return n==t?n:p(t);}

```

**Ungolfed Explanation**

```
public int powertrain(int input){
    //handles negative and 1-digit cases
    if(input<10)return input;
    //initialize output variable
    int total=1;
    // get "length" of number. Shorter than getting length of string representation
    int size=(int)Math.log10(input)+1;
    //initialize array to store digits
    int[] array=new int[size];
    //Now, because Java doesn't have support
    // for the "**" operation, and the way of turning
    // an integer into a string takes too many bytes,
    // I decided just to put every digit into an array with
    // math and iterate from there
    for(int i=1;i<=size;){
        int place=(int)Math.pow(10,i);
        //crazy math. Saved 1 byte by incrementing i when accessed
        array[size-i++]=input%place/(place/10);
    }
    for(int i=0;i<size-1;i++)
        //This is where the train happens.
        //Saved 1 byte by incrementing while accessing
        //again, instead of i+=2 and i+1
        total*=Math.pow(array[i],array[++i]);
    //Make sure last number isn't left out if size is odd
    if(size%2==1)
        total*=array[size-1];
    //if we end up with same number, stop.
    //otherwise, keep recurring
    return input==total?input:powertrain(total);
}

```

# Answer
> 2 votes
# JavaScript (ES6) 71

A recursive function, stopping when a repetition is found. This could not work for longer loops (2 or more value repeating) but it seems this could not happen, at least in the limited range of javascript number precision (17 digits)

```
f=n=>[...n+'1'].map((c,i)=>i&1?r*=Math.pow(d,c):d=c,r=1)&&n-r?f(r):n

```

**Test**

```
f=n=>[...n+'1'].map((c,i)=>i&1?r*=Math.pow(d,c):d=c,r=1)&&n-r?f(r):n

function go()
{
  v=+I.value
  R.textContent=f(v)
}

go()
```

```
<input id=I value="1234"><button onclick="go()">Go</button>
<span id=R></span>
```

# Answer
> 1 votes
# Haskell, ~~100~~ ~~79~~ 77 bytes

```
g x|x==h x=x|1<2=g$h x;h=i.map(read.(:[])).show;i[]=1;i[a]=a;i(a:b:c)=a^b*i c

```

Not golfed:

```
g x|x==h x=x|1<2=g$h x
h=i.map(read.(:[])).show
i[]=1
i[a]=a
i(a:b:c)=a^b*i c

```

This function splits the input into digits and does the trick via `i`.

EDIT: Thanks to nimi for some tips.

# Answer
> 1 votes
# MATL, 21 bytes

```
tt0>*:"V!UtQgv9L2#)^p

```

It may take a few seconds to produce the output.

*EDIT (July 30, 2016): the linked code replaces `9L` by `1L` to adapt to recent changes in the language.*

**Try it online!**

This uses the following two tricks to reduce byte count at the expense of code efficiency:

* Iterate `n` times instead of waiting until a cycle is found. This is acceptable as per OP's comments.
* For an odd number of digits a final `1` would have to be appended to complete the final power operation. Instead of that, the number of added `1` is the number of digits. This ensures an even number, so all power operations can be done (even if the last ones are unnecessary `1^1` operations).

Code:

```
t         % implicitly take input x. Duplicate
t0>*      % duplicate. Is it greater than 0? Multiply. This gives 0 if input is negative,
          % or leaves the input unchanged otherwise
:         % Generate array [1,2,...,x]
"         % for each (repeat x times)
  V       %   convert x to string
  !       %   transpose into column char array
  U       %   convert each char into number
  tQg     %   duplicate. Add 1 so that no entry is zero. Convert to logical: gives ones
  v       %   concatenate vertically
  9L2#)   %   separate odd-indexed and even-indexed entries
  ^       %   element-wise power
  p       %   product of all entries
          % implicitly end for each
          % implicitly display

```

# Answer
> 1 votes
# Mathematica, 77 bytes

```
Times@@(If[#2<1,1,#^#2]&)@@@Partition[IntegerDigits@#,2,2,1,1]&~FixedPoint~#&

```

Anonymous function. Not too complicated.

# Answer
> 1 votes
## Befunge ~~720~~ 490 bytes

Couldn't resist to do one more after the Never tell me the odds thing. So, I've optimized the "ASCII-fier" of the previous one. In this case I saw no need to let the instruction pointer run over the digits to read them, so I haven't taken the effort to make them human readable. So it's more of a digitifier, now.

Again, if you guys want an explanation, let me know in the comments, I'll try to create some helpful descriptions. You can copy paste the code into the interpreter. I've found that the example 24547284284866560000000000 outputs 0, but that seems to be a problem with getting such a large value from a point on the grid, as you can clearly see the correct value being stored in the final steps.

```
v                                                    //top row is used for "variables"
>&:0`#v_.@                                           //initialize the counter
v     <                           g01_v#-p01:  <     //on our way back to the digitifier, check if we're done
>::>210p>55+%:10g0p-55+/:v            >10g.@         //digitifier, creates a series of ASCII characters at the top line, one for each digit in the source
        ^p01+1g01    _v#:<
v1$$                  <                              //forget some remainders of the digitifier, put 1 on the stack as a base of calculation
                      v p0-1g01-1g0-1g01*g0g01<      //taking powers of each pair of digit
>10g2-!#v_10g1-!#v_  1>                10g1-0g|
^                                  p01-2g01  *<
        >10g0g*  >                             ^     //extra multiplication with last digit if the number of digits was odd

```

This version also supports negative input. It's a great improvement on the previous version, if I say so myself. At least 1 bug was fixed and the size was reduced greatly.

# Answer
> 1 votes
# Mathematica, 74 bytes

```
0~f~0=f[]=1
f@n_=n
f[a_,b_,c___]:=f[c]a^b
#//.i_/;i>0:>f@@IntegerDigits@i&

```

**Explanation**

This solution uses a helper function `f`, which takes the digits of the number as arguments and applies one iteration of the power train operation. The last line is a pure function that is crafted to exploit the `ReplaceRepeated` function (or `//.` for short), which applies a rule to an expression (in this case the argument `#` of the pure function) until it doesn't change anymore. The rule `i_/;i>0:>f@@IntegerDigits@i` replaces anything non-negative with the function `f` applied to its decimal digits.

# Answer
> 0 votes
## Python 3, ~~169~~ 161 bytes

```
def f(s):
 o=[['1',s]['-'in s]]
 while s not in o:
  o+=[s];s+='1'*(len(s)%2==1);r=1;
  for i,j in zip(s[::2],s[1::2]):r*=int(i)**int(j);s=str(r);
 return o[-1]

```

**Ungoldfed**

```
def f(s):
 o=[['1',s]['-'in s]]
 while s not in o:
  o+=[s]
  s+='1'*(len(s)%2==1)
  r=1
  for i,j in zip(s[::2],s[1::2]):
   r*=int(i)**int(j)
  s=str(r)
 return o[-1]

```

## Results

```
>>> [f(i) for i in ['135', '1234', '642', '2592', '-15']]
['5', '8', '2592', '2592', '-15']

```

# Answer
> 0 votes
# Oracle SQL 11.2, 456 bytes

```
WITH v(n,c,i,f,t)AS(SELECT:1+0,CEIL(LENGTH(:1)/2),1,'1',0 FROM DUAL UNION ALL SELECT DECODE(SIGN(c-i+1),-1,t,n),DECODE(SIGN(c-i+1),-1,CEIL(LENGTH(t)/2),c),DECODE(SIGN(c-i+1),-1,1,i+1),DECODE(SIGN(c-i+1),-1,'1',RTRIM(f||'*'||NVL(POWER(SUBSTR(n,i*2-1,1),SUBSTR(n,i*2,1)),SUBSTR(n,i*2-1,1)),'*')),DECODE(SIGN(c-i+1),-1,0,TO_NUMBER(column_value))FROM v,XMLTABLE(f)WHERE i<=c+2 AND:1>9)CYCLE n,c,i,f,t SET s TO 1 DEFAULT 0SELECT NVL(SUM(n),:1) FROM v WHERE s=1;

```

Un-golfed

```
WITH v(n,c,i,f,t) AS
(
  SELECT :1+0,CEIL(LENGTH(:1)/2),1,'1',0 FROM DUAL
  UNION ALL
  SELECT DECODE(SIGN(c-i+1),-1,t,n),
         DECODE(SIGN(c-i+1),-1,CEIL(LENGTH(t)/2),c),
         DECODE(SIGN(c-i+1),-1,1,i+1),
         DECODE(SIGN(c-i+1),-1,'1',RTRIM(f||'*'||NVL(POWER(SUBSTR(n,i*2-1,1),SUBSTR(n,i*2,1)),SUBSTR(n,i*2-1,1)),'*')),
         DECODE(SIGN(c-i+1),-1,0,TO_NUMBER(column_value))
  FROM v,XMLTABLE(f) WHERE i<=c+2 AND :1>9
)
CYCLE n,c,i,f,t SET s TO 1 DEFAULT 0
SELECT NVL(SUM(n),:1) FROM v WHERE s=1;

```

v is a recursive view, parameters are

n : number to split in 2 digits parts

c : number of 2 digits parts

i : current 2 digits part to compute

f : string concatenating the powers with * as separator

t : evaluation of f

The DECODEs switch to the next number to split and compute when all the parts of the current number are done.

XMLTABLE(f) takes an expression an evaluates it, putting the result in the pseudo column "column\_value". It's the golfed version of http://tkyte.blogspot.fr/2010/04/evaluating-expression-like-calculator.html

CYCLE is the oracle build in cycle detection and is used as the exit condition.

Since the result for :1\<10 is :1 and v returns no row for those cases, SUM forces a row with NULL as the value. NVL returns :1 as the result if the row is null.

# Answer
> 0 votes
# Husk, 10 bytes

```
ωöΠmF`^C2d

```

Try it online!

## Explanation

```
ωöΠmF`^C2d
ωö         apply the following functions till a fixed point is reached:
         d get base-10 digits
       C2  split into groups of two
   mF`^    map each pair to power
  Π        multiply all the powers.

```

# Answer
> 0 votes
# Japt, 13 bytes

```
Èì ò ®rpÃ×}gN

```

Try it

---
Tags: code-golf, math
---


title: Float 754 to Hamming

text:
# Question
Title: Float 754 to Hamming
You will be given as **input** an integer `k` in the range from `-4503599627370496` (−252) to `4503599627370496` (252). As is well known, integers in this range can be represented exactly as double-precision floating-point values.

You should **output** the Hamming weight (number of ones) of the encoding of `k` in binary64 format. This uses 1 bit for the sign, 11 bits for the exponent (encoded with an offset), and 52 for the mantissa; see the above link for details.

As an **example**, number `22` is represented as

```
0 10000000011 0110000000000000000000000000000000000000000000000000

```

Since there are `5` ones, the output is `5`.

Note that endianness doesn't affect the result, so you can safely use your machine's actual internal representation of double-precision values to compute the output.

### Additional rules

### Test cases

```
22                ->   5
714               ->   6
0                 ->   0
1                 ->  10
4503599627370496  ->   5
4503599627370495  ->  55
1024              ->   3
-1024             ->   4
-4096             ->   5
1000000000        ->  16
-12345678         ->  16

```

# Answer
# MATL, 5 bytes

```
3Z%Bz

```

Try it online!

Exact transliteration of my MATLAB answer. Note that input and output are implicit. -2 bytes thanks to Luis Mendo.

```
3Z%   % Typecast: changes input (implicitly taken and converted to double) to uint64 without changing underlying bits
B     % Convert integer to array of 1s and 0s
z     % Count nonzero entries

```
> 9 votes

# Answer
# x86\_64 machine language (Linux), 16 bytes

```
0:       f2 48 0f 2a c7          cvtsi2sd %rdi,  %xmm0
5:       66 48 0f 7e c0          movq     %xmm0, %rax
a:       f3 48 0f b8 c0          popcnt   %rax,  %rax
f:       c3                      retq

```

Accepts a single 64-bit integer parameter in `RDI`, converts it to a floating-point value in `XMM0`, stores those bits back in `RAX`, and then computes the hamming weight of `RAX`, leaving the result in `RAX` so it can be returned to the caller.

Requires a processor that supports the `POPCNT` instruction, which would be Intel Nehalem, AMD Barcelona, and later microarchitectures.

To Try it online!, compile and run the following C program:

```
#include<stdio.h>
const char g[]="\xF2\x48\x0F\x2A\xC7\x66\x48\x0F\x7E\xC0\xF3\x48\x0F\xB8\xC0\xC3";
#define f(x) ((int(*)(long))g)(x)

int main(int a){
  printf("%d\n",f(22));
  printf("%d\n",f(714));
  printf("%d\n",f(0));
  printf("%d\n",f(1));
  printf("%d\n",f(4503599627370496L));
  printf("%d\n",f(4503599627370495L));
  printf("%d\n",f(1024));
  printf("%d\n",f(-1024));
  printf("%d\n",f(-4096));
  printf("%d\n",f(1000000000));
  printf("%d\n",f(-12345678));
}

```

Edit: Fixed segfault in TIO link.
> 35 votes

# Answer
# C (gcc), ~~82~~ 68 bytes

9 bytes thanks to Neil.

evil floating point bit level hacking

```
s;f(long n){double d=n;n=*(long*)&d;for(s=0;n;n*=2)s+=n<0;return s;}

```

Try it online!
> 12 votes

# Answer
# Python 3, ~~72~~ 71 bytes

1 byte thanks to Lynn.

```
lambda n:n and(bin(1020+len(bin(abs(n))))+bin(abs(n))).count('1')-(n>0)

```

Try it online!

### Explanation

The binary64 format consists of three components:

* the first bit is the sign bit, which is `1` if the number is negative
* the next 11 bits store the exponent with 1023 added
* the next 52 bits store the significand, or the mantissa.
> 9 votes

# Answer
# C (gcc), 47 bytes

```
f(double n){n=__builtin_popcountl(*(long*)&n);}

```

This isn't portable; it was tested with gcc 7.1.1 on x86\_64 running Linux, without compiler flags.

Try it online!
> 8 votes

# Answer
# Java (OpenJDK 8), 92 bytes

```
int f(long n){int s=0;for(n=Double.doubleToLongBits((double)n);n!=0;n>>>=1)s+=n&1;return s;}

```

Try it online!
> 7 votes

# Answer
# C (gcc), 63 bytes

```
f(double d){long s=0,n=*(long*)&d;for(;n;n*=2)s+=n<0;return s;}

```

This solution is based on @LeakyNun's answer, but because he doesn't want to improve his own answer, I'm posting here more golfed version.

Try it online
> 6 votes

# Answer
# C#, ~~81~~ ~~70~~ 68 bytes

```
d=>{unsafe{long l=*(long*)&d,s=0;for(;l!=0;l*=2)s-=l>>63;return s;}}

```

*Save 11 bytes thanks to @Leaky Nun.*
*Saved 2 bytes thanks to @Neil.*

Try it online! Uses `System.BitConverter.DoubleToInt64Bits` instead of the `unsafe` code as I couldn't get TIO to work with it.

Full/Formatted Version:

```
namespace System
{
    class P
    {
        static void Main()
        {
            Func<double, long> f = d =>
            {
                unsafe
                {
                    long l = *(long*)&d, s = 0;

                    for (; l != 0; l *= 2)
                        s -= l >> 63;
                    return s;
                }
            };

            Console.WriteLine(f(22));
            Console.WriteLine(f(714));
            Console.WriteLine(f(0));
            Console.WriteLine(f(1));
            Console.WriteLine(f(4503599627370496));
            Console.WriteLine(f(4503599627370495));
            Console.WriteLine(f(1024));
            Console.WriteLine(f(-1024));
            Console.WriteLine(f(-4096));
            Console.WriteLine(f(1000000000));
            Console.WriteLine(f(-12345678));

            Console.ReadLine();
        }
    }
}

```
> 5 votes

# Answer
## JavaScript (ES6), ~~81~~ ~~80~~ ~~77~~ 76 bytes

```
f=
n=>new Uint8Array(Float64Array.of(n).buffer).map(g=i=>i&&g(i&i-1,x++),x=0)|x
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>0
```

Edit: Saved 1 byte thanks to @Arnauld. Saved 3 bytes thanks to @DocMax. Saved 1 byte thanks to @l4m2.
> 4 votes

# Answer
# Python 2, 69 bytes

-12 bytes, thanks to @ASCII-only

```
lambda n:bin(*unpack('Q',pack('d',n))).count('1')
from struct import*

```

Try it online!
> 4 votes

# Answer
# Perl 5, ~~33~~ 32 + 1 (-p) = ~~34~~ 33 bytes

*Saved 1 byte thanks to hobbs*

```
$_=(unpack"B*",pack d,$_)=~y/1//

```

Try it online!
> 4 votes

# Answer
# x86-64 machine code, 12 bytes for `int64_t` input

# 6 bytes for `double` input

Requires the `popcnt` ISA extension (`CPUID.01H:ECX.POPCNT [Bit 23] = 1`).

(Or 13 bytes if modifying the arg in-place requires writing all 64-bits, instead of leaving garbage in the upper 32. I think it's reasonable to argue that the caller would probably only want to load the low 32b anyway, and x86 zero-extends from 32 to 64 implicitly with every 32-bit operation. Still, it does stop the caller from doing `add rbx, [rdi]` or something.)

x87 instructions are shorter than the more obvious SSE2 `cvtsi2sd`/`movq` (used in @ceilingcat's answer), and a `[reg]` addressing mode is the same size as a `reg`: just a mod/rm byte.

The trick was to come up with a way to have the value passed in memory, without needing too many bytes for addressing modes. (e.g. passing on the stack isn't that great.) Fortunately, the rules allow read/write args, or separate output args, so I can just get the caller to pass me a pointer to memory I'm allowed to write.

Callable from C with the signature: `void popc_double(int64_t *in_out);` Only the low 32b of the result is valid, which is maybe weird for C but natural for asm. (Fixing this requires a REX prefix on the final store (`mov [rdi], rax`), so one more byte.) On Windows, change `rdi` to `rdx`, since Windows doesn't use the x86-64 System V ABI.

NASM listing. The TIO link has the source code without the disassembly.

```
  1  addr    machine      global popcnt_double_outarg
  2          code         popcnt_double_outarg:
  3                           ;; normal x86-64 ABI, or x32: void pcd(int64_t *in_out)
  4 00000000 DF2F             fild qword  [rdi]    ; int64_t -> st0
  5 00000002 DD1F             fstp qword  [rdi]    ; store binary64, using retval as scratch space.
  6 00000004 F3480FB807       popcnt rax, [rdi]
  7 00000009 8907             mov    [rdi], eax    ; update only the low 32b of the in/out arg
  8 0000000B C3               ret
    # ends at 0x0C = 12 bytes

```

**Try it online!** Includes a `_start` test program that passes it a value and exits with exit status = popcnt return value. (Open the "debug" tab to see it.)

Passing separate input/output pointers would also work (rdi and rsi in the x86-64 SystemV ABI), but then we can't reasonably destroy the 64-bit input or as easily justify needing a 64-bit output buffer while only writing the low 32b.

If we do want to argue that we can take a pointer to the input integer and destroy it, while returning output in `rax`, then simply omit the `mov [rdi], eax` from `popcnt_double_outarg`, bringing it down to 10 bytes.

---

## Alternative without silly calling-convention tricks, 14 bytes

use the stack as scratch space, with `push` to get it there. Use `push`/`pop` to copy registers in 2 bytes instead of 3 for `mov rdi, rsp`. (`[rsp]` always needs a SIB byte, so it's worth spending 2 bytes to copy `rsp` before three instructions that use it.)

Call from C with this signature: `int popcnt_double_push(int64_t);`

```
 11                               global popcnt_double_push
 12                               popcnt_double_push:
 13 00000040 57                       push   rdi         ; put the input arg on the stack (still in binary integer format)
 14 00000041 54                       push   rsp         ; pushes the old value (rsp updates after the store).
 15 00000042 5A                       pop    rdx         ; mov      rdx, rsp
 16 00000043 DF2A                     fild   qword [rdx]
 17 00000045 DD1A                     fstp   qword [rdx]
 18 00000047 F3480FB802               popcnt rax,  [rdx]
 19 0000004C 5F                       pop    rdi         ; rebalance the stack
 20 0000004D C3                       ret
    next byte is 0x4E, so size = 14 bytes.

```

---

# Accepting input in `double` format

The question just says it's an integer in a certain range, not that it has to be in a base2 binary integer representation. Accepting `double` input means there's no point in using x87 anymore. (Unless you use a custom calling convention where `double`s are passed in x87 registers. Then store to the red-zone below the stack, and popcnt from there.)

**11 bytes:**

```
 57 00000110 66480F7EC0               movq    rax, xmm0
 58 00000115 F3480FB8C0               popcnt  rax, rax
 59 0000011A C3                       ret

```

But we can use the same pass-by-reference trick as before to make a 6-byte version: `int pcd(const double&d);`

```
 58 00000110 F3480FB807               popcnt  rax, [rdi]
 59 00000115 C3                       ret

```

**6 bytes**.
> 4 votes

# Answer
## MATLAB, 36 bytes

```
@(n)nnz(de2bi(typecast(n,'uint64')))

```

Using the fact that `de2bi` is not only shorter than `dec2bin`, but also provides a result in ones and zeroes rather than ASCII 48, 49.
> 3 votes

# Answer
# Java (64, 61, 41 bytes)

Completely straightforward using the standard library (Java SE 5+):

```
int f(long n){return Long.bitCount(Double.doubleToLongBits(n));}
```

Contribution by Kevin Cruijssen (Java SE 5+):

```
int f(Long n){return n.bitCount(Double.doubleToLongBits(n));}

```

Contribution by Kevin Cruijssen (Java SE 8+, lambda function):

```
n->n.bitCount(Double.doubleToLongBits(n))

```
> 3 votes

# Answer
# JavaScript (Node.js), ~~79~~76 bytes

```
n=>n&&((g=n=>t=n.toString(2))(n)+g(t.length*2-(n<0)+2044)).split`1`.length-2

```

Try it online!

~~First answer not relying on cast?~~ At least this is earlier
> 3 votes

# Answer
Just to try a different, safer-than-TheLethalCoder's approach, I came up with this (it's a pity C# has such long method names):

# C# (.NET Core), 76+13 bytes

```
d=>Convert.ToString(BitConverter.DoubleToInt64Bits(d),2).Split('1').Length-1

```

Try it online!

Byte count includes 13 bytes for `using System;`. First I need to convert the `double` to a `long` that has the same binary representation, then I can convert it to a binary `string`, and then I count the `1`s just by splitting the string and counting the substrings minus 1.
> 2 votes

# Answer
# Jelly, 19 bytes

```
AB©L+⁽¡ßB;®ċ1_>0$a@

```

Try it online!
> 2 votes

# Answer
# Erlang 55 bytes

```
fun(X)->length([Y||<<Y:1>><=<<X:64/float>>,Y=:=1])end.

```

An anonymous function that counts all the `1`s in a number encoded as a 64 bit float.

references:
> 1 votes

# Answer
# dc, 79 bytes

```
[pq]su[-1r]st0dsb?dd0=u0>tsa[1+]ss[la2%1=slb1+sblad2/sa1<r]dsrxlb1022+sa0lrx+1-

```

Output is left on top of the stack.
I'll add an explanation later.

Try it online!

Note that negative numbers are preceded by `_`, not `-`.
> 1 votes

# Answer
# Groovy (with Parrot parser), 46 bytes

```
f=n->Long.bitCount(Double.doubleToLongBits(n))

```
> 1 votes

# Answer
# C, 67 bytes

```
int i;g(char*v){int j=v[i/8]&1<<i%8;return!!j+(++i<64?g(v):(i=0));}

```

control code and results

```
#define R     return
#define u32 unsigned
#define F        for
#define P     printf

int main()
{/*           5   6 0 10                5               55    3      4       16*/
 double v[]={22,714,0,1 ,4503599627370496,4503599627370495,1024, -1024, -12345678};
 int i;

 F(i=0;i<9;++i)
     P("%f = %d\n", v[i], g(&v[i]));
 R 0;
}

>tri4
22.000000 = 5
714.000000 = 6
0.000000 = 0
1.000000 = 10
4503599627370496.000000 = 5
4503599627370495.000000 = 55
1024.000000 = 3
-1024.000000 = 4
-12345678.000000 = 16

```
> 1 votes

# Answer
# Husk, 20 bytes

```
&->0±¹ΣS+ȯḋ+1022Lḋa¹

```

Try it online! A port of Leaky Nun's Python 3 answer.
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
ĀiÄbDgŽ42+b«1¢Id-

```

Port of *@LeakyNun*'s Python 3 answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
Āi                 # If the (implicit) input-integer is NOT 0:
  Ä                #  Take the absolute value of the (implicit) input-integer
   b               #  Convert it to binary
    Dg             #  Duplicate it, then pop and push its length
      Ž42+         #  Add compressed integer 1022 to this length
          b        #  Convert it to binary as well
           «       #  Merge the two binary-strings together
            1¢     #  Count the amount of 1s in this string
              Id   #  Check that the input-integer is non-negative (1 if >=0; 0 if <0)
                -  #  Subtract that from the count
                   #  (after which it is output implicitly as result)
                   # (implicit else: output the implicit input, which is 0)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž42` is `1022`.
> 1 votes

# Answer
# Rust, 27 bytes

```
|n|n.to_bits().count_ones()

```

Try it online!

An anonymous function that takes in an f64 and outputs a u32. The `to_bits` function reinterprets the bits of an f64 into a u64, where I can use the convenient `count_ones` function to trivialize the problem.
> 0 votes

---
Tags: code-golf, integer, floating-point
---


# Question
Title: Find the number of x-digit numbers whose product of digits is N
Given two numbers \\$N\\$ and \\$x\\$, find the number of \\$x\\$-digit numbers whose product of digits is \\$N\\$

\\$N \<10^6\\$ and \\$x \<12\\$

```
Sample Input (N x):
8 3
Sample Output:
10

```

# Answer
> 3 votes
### Golfscript ~~42~~ 31

```
~10\?.10/\,>{10base{*}*1$=},,\;

```

**Input:** Expects the numbers `N` and `x` as command line arguments (separated by space).

The program can be tested here.

# Answer
> 2 votes
# Brachylog 2, 13 bytes

```
{h.&t~lℕẹ≜×}ᶜ

```

Try it online!

## Explanation

```
{h.&t~lℕẹ≜×}ᶜ
{          }ᶜ   Count the number of
         ≜      values at this point
   &t           formed via taking the last element of the input,
       ℕ        generating an integer
     ~l         of that length,
        ẹ       and splitting it into digits
          ×     such that the product of those digits
 h.             is the first element of {the input}

```

One neat golfing trick used here is that unlike almost all metapredicates,  doesn't care at all about the actual value of `.` (which is normally used to construct an output for the metapredicates); as such, `.` can be used like any other variable (saving a byte because it appears implicitly before `}`). There are no implicit labelisations anywhere here, so I had to add an explicit labelisation using  to give  something to count.

# Answer
> 1 votes
## Scala 107:

```
def f(N:Int,x:Int,s:Int=1):Int=if(s==N&&x==0)1 else
if(s>N||x==0)0 else
((1 to 9).map(i=>f(N,x-1,s*i))).sum

```

ungolfed, debugfriendly version:

```
def findProduct (N: Int, sofar: Int, togo:Int, collected:String=""):Int={
  if (sofar == N && togo == 0) {
    println (collected)
    1
  } else
  if (sofar > N || togo == 0) 0 else
  (1 to 9).map (x=> findProduct (N, sofar*x, togo-1, collected + " " + x)).sum
}

```

Invocation with debugging output:

```
scala> findProduct (3, 1, 8)
 1 1 1 1 1 1 1 3
 1 1 1 1 1 1 3 1
 1 1 1 1 1 3 1 1
 1 1 1 1 3 1 1 1
 1 1 1 3 1 1 1 1
 1 1 3 1 1 1 1 1
 1 3 1 1 1 1 1 1
 3 1 1 1 1 1 1 1
res175: Int = 8

scala> findProduct (8, 1, 3)
 1 1 8
 1 2 4
 1 4 2
 1 8 1
 2 1 4
 2 2 2
 2 4 1
 4 1 2
 4 2 1
 8 1 1
res176: Int = 10

```

# Answer
> 1 votes
# Jelly, 7 bytes

```
⁵Ḷṗ⁸P€ċ

```

Try it online!

Fun fact, this (as far as I can tell) would've worked, atom-for-atom, when ais523's answer was posted.

## How it works

```
⁵Ḷṗ⁸P€ċ - Main link. Takes N on the left and x on the right
⁵       - 10
 Ḷ      - Ḷowered range; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   ⁸    - N
  ṗ     - Cartesian power; Yield all N-length sublists of [0, 1, ..., 9]
     €  - Over each:
    P   -   Take the product
      ċ - Count occurrences of x

```

# Answer
> 0 votes
# Python, 164 bytes

```
from itertools import *
N,x=map(int,raw_input().split())
print len([c for c in product([d for d in range(1,10)if N%d==0],repeat=x) if reduce(lambda x,y:x*y,c)==N])

```

# Answer
> 0 votes
### C# 128

```
int Z(int n,int x){var i=(int)Math.Pow(10,x-1);return Enumerable.Range(i,i*9).Count(j=>(j+"").Aggregate(1,(a,c)=>a*(c-48))==n);}

```

This C# method returns the number of `x`-digit numbers whose product of digits is `n`. It requires that namespaces `System` and `System.Linq` are imported in the current context.

Online version: http://ideone.com/0krup

# Answer
> 0 votes
## Haskell 117 chars

```
import Data.Char
main = print $ f 3 8
f n t = length[x|x<-[10^(n-1)..(10^n-1)],foldr(*)1(map digitToInt $ show x)==t]

```

# Answer
> 0 votes
# K, 49

```
{+/x=*/'"I"$''${x@&~x in y}.!:'"i"$10 xexp y,y-1}

```

.

```
k){+/x=*/'"I"$''${x@&~x in y}.!:'"i"$10 xexp y,y-1}[8;3]
10

```

# Answer
> 0 votes
# J, 40 bytes

```
[:+/[=[:*/"1(10#~])#:(10^<:@])}.[:i.10^]

```

Generates all `x`-digit numbers, convert each to base 10, then find the product of each number, and test whether each number is equal to the left hand side, and then find the sum of each boolean.

# Answer
> 0 votes
# Jelly, 12 bytes

```
,’⁵*r/ḊDP€ċƓ

```

Try it online!

Takes \\$x\\$ as a command line argument and \\$N\\$ on standard input.

## Explanation

```
,’⁵*r/ḊDP€ċƓ
,             On {the input} and
 ’            {the input} minus 1
  ⁵*          take 10 to the power of each of those numbers
    r/        then form a range between them
      Ḋ       without its first element;
       D      treat each element as a list of digits,
        P€    take the product of each of those digit lists,
          ċ   then count the number of times
           Ɠ  the value from standard input appears

```

The hard part is generating the list of numbers with *x* digits; the lowest such number is \\$10^{x-1}\\$, the highest is \\$10^x-1\\$ The range here is generated via first generating the pair \\$(x,x-1)\\$, then taking 10 to the power of both of those, and then generating the range between them. The range includes both endpoints by default; just in case *N* happens to be 0, we need to remove the top end of the range (which comes first because it's a "backwards" range) using .

---
Tags: code-golf, number-theory
---


title: Some Prime Peerage

text:
# Question
Title: Some Prime Peerage
*(Randomly inspired by https://mathoverflow.net/q/339890)*
*(Related: , )*

Given an input list of distinct prime numbers (e.g., `[2, 5, 7]`), and a integer `n`, output all positive integers strictly smaller than `n` that contain only those primes as divisors. For input `[2, 5, 7]` and `n=15` this means an output of `[2, 4, 5, 7, 8, 10, 14]`.

**Further Examples**

```
[list] n | output

[2, 5, 7] 15 | [2, 4, 5, 7, 8, 10, 14]
[2, 5, 7] 14 | [2, 4, 5, 7, 8, 10]
[2] 3 | [2]
[2] 9 | [2, 4, 8]
[103, 101, 97] 10000 | [97, 101, 103, 9409, 9797, 9991]
[97, 101, 103] 104 | [97, 101, 103]

```

**Rules and Clarifications**

* The input list is guaranteed non-empty, but may be only a single element
* You can assume the input list is pre-sorted in whatever way is most convenient
* `n` will always be larger than the largest element in the input list
* Since, e.g., `2**0 = 1`, you can optionally include `1` in your output list
* Input and output can be given by any convenient method
* You can print the result to STDOUT or return it as a function result
* Either a full program or a function are acceptable
* If applicable, you can assume the input/output integers fit in your language's native `int` range
* Standard loopholes are forbidden
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins

# Answer
> 5 votes
# 05AB1E, ~~6~~ 5 bytes

```
PmÑʒ›

```

-1 byte thanks to *@ovs* (and *@Grimmy*, who provided `sиPÑʒ›` as 6 bytes alternative initially).

Takes the list as first input, and integer as second. Includes the optional `1` in the output.
Extremely slow approach (the `[2,5,7], 15` test case already times out).

Try it online. (No test suite, because it's too slow for most.)

**Explanation:**

```
P      # Take the product of the (implicit) input-list
       #  i.e. [2,5] → 10
 m     # Take the (implicit) input-integer to the power this product
       #  i.e. 10 → 10000000000
  Ñ    # Get all divisors of this integer
       # (the bottleneck for larger integers in this approach)
       #  → [1,2,4,5,8,10,16,20,25,32,40,50,64,80,100,125,128,160,200,250,256,320,400,500,512,625,640,800,1000,1024,1250,1280,1600,2000,2500,2560,3125,3200,4000,5000,5120,6250,6400,8000,10000,12500,12800,15625,16000,20000,25000,25600,31250,32000,40000,50000,62500,64000,78125,80000,100000,125000,128000,156250,160000,200000,250000,312500,320000,390625,400000,500000,625000,640000,781250,800000,1000000,1250000,1562500,1600000,1953125,2000000,2500000,3125000,3200000,3906250,4000000,5000000,6250000,7812500,8000000,9765625,10000000,12500000,15625000,16000000,19531250,20000000,25000000,31250000,39062500,40000000,50000000,62500000,78125000,80000000,100000000,125000000,156250000,200000000,250000000,312500000,400000000,500000000,625000000,1000000000,1250000000,2000000000,2500000000,5000000000,10000000000]
   ʒ   # Filter this list of divisors:
    ›  #  Only keep those where the (implicit) input-integer is larger than the divisor
       #  → [1,2,4,5,8]
       # (after the filter, the result is output implicitly)

```

---

**Two faster 6 bytes alternatives:**

```
<LʒfåP

```

Takes the integer as first input, list as second. Includes the optional `1` in the output.

Try it online or verify all test cases.

**Explanation:**

```
<       # Decrease the (implicit) input by 1
 L      # Create a list in the range [1,input-1]
  ʒ     # Filter it by:
   f    #  Get all prime factors of the current number (without duplicates)
    å   #  Check for each if its in the (implicit) input-list
     P  #  And check if this is truthy for all
        # (after the filter, the result is output implicitly)

```

---

Thanks to *@Grimmy*:

```
GNfåP–

```

Try it online or verify all test cases.

```
G       # Loop `N` in the range [1, (implicit) input):
 Nf     #  Get all prime factors of `N` (without duplicates)
   å    #  Check for each if its in the (implicit) input-list
    P   #  And check if this is truthy for all
     –  #  If it is, output the current `N` with trailing newline

```

# Answer
> 5 votes
# Stax, 6 bytes

```
Ç─☼?▬µ

```

Run and debug it at staxlang.xyz!

### Unpacked (7 bytes) and explanation:

```
vf:Fn-!
vf         Filter range [1..n-1]:
  :F         Distinct prime factors
    n-       Remove all in provided list
      !      Is empty?

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~64 ... 52~~  50 bytes

Takes input as `(n)(primes)` where *primes* is a set. Outputs by modifying the set.

```
n=>g=(s,q=1)=>{for(p of s)(p*=q)<n&&g(s.add(p),p)}

```

Try it online!

### Commented

```
n =>              // n = maximum value
g = (             // g is a recursive function taking:
  s,              //   s = set of primes
  q = 1           //   q = current product, initialized to 1
) => {            //
  for(p of s)     // for each value p in s:
    (p *= q)      //   multiply p by q
    < n &&        //   if the result is less than n:
      g(          //     do a recursive call:
        s.add(p), //       with p added to the set
        p         //       with q = p
      )           //     end of recursive call
}                 //

```

# Answer
> 4 votes
# Python 3, ~~68~~ 65 bytes

```
f=lambda s,n,c=1:n//c*s and f(s,n,s[0]*c)+f(s[1:],n,c)or[c][:c<n]

```

Try it online!

*-3 bytes thanks to @xnor*

The function takes a prime sequence and an integer n as inputs. The output is a list that includes 1.

# Ungolfed:

```
def f(s, n, c=1):
    if not c < n:
       return []
    elif not s:
       return [c]
    else:
       return f(s,n,s[0]*c) + f(s[1:],n,c)

```

Try it online!

# Answer
> 3 votes
# Haskell, 51 bytes

For each prime `x` in the list of primes `p` the expression `mapM((<$>[0..n]).(^))p` computes all powers \\$1,x,x^2,\ldots,x^n\\$ (where \\$n\\$ is the second input just used as an upper bound) and then the cartesian product of all these sequences. After that we compute the `product` of all entries of this cartesian product and filter out all that are too large.

This means that it is incredibly slow or might even crash if `n` is large or the list of primes `p` is large, as this cartesian product contains \\$(\\#p)^n\\$ entries.

```
p#n=[k|k<-product<$>mapM((<$>[0..n]).(^))p,k<n,k>1]

```

Try it online!

# Answer
> 3 votes
# Haskell, 39 bytes

```
l%n=[k|k<-[2..n-1],mod(product l^k)k<1]

```

Try it online!

Checks if `k` is divisible only by primes in `l` by seeing if the product of `l` taken to a high power is divisible by `k`.

# Answer
> 3 votes
# Python 2, 65 bytes

```
lambda l,n:[k for k in range(2,n)if reduce(int.__mul__,l)**n%k<1]

```

Try it online!

Checks if `k` is divisible only by primes in `l` by seeing if the product of `l` taken to a high power is divisible by `k`.

If `l` can be taken as a list of strings `eval("*".join(l))` saves 3 bytes over `reduce(int.__mul__,l)` and can be used in Python 3 which lacks `reduce`.

**Python 3, 64 bytes**

```
def f(l,n,P=1):
 for x in l:P*=x
 n-=1;P**n%n or print(n);f(l,n)

```

Try it online!

A function the prints in reverse order and terminates with error.

The recursive solution below would be shorter if `n` itself were included in the list. I tried recursively computing the product of `l` as well, but that was longer.

**62 bytes (non-working)**

```
f=lambda l,n:n*[f]and[n][reduce(int.__mul__,l)**n%n:]+f(l,n-1)

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), 25 bytes SBCS

```
{⍺{v/⍨⍺>v←∪,∘.×⍨⍵}⍣⍺⊢1,⍵}

```

Try it online!

**How it works**:

The main idea of this solution is that we take the input primes , we prepend 1 to them with `1,⍵` and we multiply these numbers all together a bunch of times, where "a bunch of times" is the `n` input (refered to by ). This repetition is controlled by `⍣⍺`. What we actually repeat is the inner dfn

`{v/⍨⍺>v←∪,∘.×⍨⍵}`

This dfn takes as  the input `n` and as  the multiplications we have so far. Then, `∘.×⍨⍵` multiplies all those accumulated multiplications so far with themselves, into a matrix that looks like a "times table" of  with itself.

Then `∪,` flattens and removes duplicates and assigns that to `v` with `v←`.

Finally, `v/⍨⍺>v` filters out elements greater than or equal to , which is the `n` input.

# Answer
> 1 votes
# Gaia, 10 bytes

```
…@e⟪ḍ‡⁻!⟫⁇

```

Try it online!

I've never used  with a monad before, it's quite helpful for stack manipulation.

```
…		| push [0..n-1]
@e		| push list of primes
  ⟪    ⟫⁇	| filter [0..n-1] for where the following predicate is true:
   ḍ‡		| the list of prime factors
     ⁻		| minus the list of primes
      !		| is empty

```

# Answer
> 1 votes
# , 24 bytes

```
(]#~0=1#.(-."1~q:))2}.i.

```

Try it online!

# Answer
> 1 votes
# Jelly, 7 bytes

```
ṖÆffƑ¥Ƈ

```

Try it online!

A dyadic link taking the exclusive upper bound as its left argument and the list of primes as its right. Returns a list that includes 1 as well as the numbers only composed of the supplied primes.

An alternative 7 would be `ṖÆfḟ¥Ðḟ`

# Answer
> 1 votes
# Python 2, 98 bytes

```
lambda a,n:[i for i in R(2,n)if{p for p in R(2,i+1)if(i%p<1)*all(j%p for j in R(2,p))}<=a]
R=range

```

Try it online!

# Answer
> 0 votes
# Japt `-f`, ~~11~~ 8 bytes

```
k
è@e!øV

```

Try it

# Answer
> 0 votes
# Japt `-f`, 7 bytes

```
©k e!øV

```

Try it

# Answer
> 0 votes
# Ruby `-rprime`, 61 bytes

```
->n,l{(2..n).select{|i|i.prime_division.all?{|b,|[b]-l==[]}}}

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 64 bytes

```
\d+
$*
\G1
$.`,$`;
+`,(1+)(\1)*(?=;.* \1\b)
,1$#2$*
!`\d+(?=,1;)

```

Try it online! List includes smaller test cases (`10000` times out because of all the long strings). Takes input in the order `n f1 f2 f3...` (factors do not need to be prime but they do need to be coprime). Output includes `1`. Explanation:

```
\d+
$*

```

Convert to unary.

```
\G1
$.`,$`;

```

Generate a list from 0 to `n-1`, in both decimal and unary.

```
+`,(1+)(\1)*(?=;.* \1\b)
,1$#2$*

```

Repeatedly divide the unary by any available factors.

```
!`\d+(?=,1;)

```

Output the decimal numbers where the unary number has been reduced to `1`.

# Answer
> 0 votes
# Charcoal, ~~22~~ 20 bytes

```
ＩΦ…²η⬤…·²ι∨﹪ιλ⊙θ¬﹪λν

```

Try it online! Link is to verbose version of code. Too slow for the larger test case. Explanation:

```
 Φ                      Filter on
  …                     Range from
   ²                    Literal `2` to
    η                   Input limit
     ⬤                  Where all values
      …·                Inclusive range from
        ²               Literal `2` to
         ι              Filter value
          ∨             Either
             λ          Inner value
           ﹪            Is not a divisor of
            ι           Filter value
              ⊙         Or any of
               θ        Input primes
                   ν    Current prime
                ¬﹪      Is a divisor of
                  λ     Inner value
Ｉ                       Cast to string for implicit print

```

Previous faster 22-byte answer:

```
⊞υ¹ＦυＦ×ιθＦ›‹κη№υκ⊞υκＩυ

```

Try it online! Link is to verbose version of code. Output includes `1`. Explanation:

```
⊞υ¹

```

Push `1` to the predefined empty list.

```
Ｆυ

```

Loop over the list, including any items pushed to it during the loop.

```
Ｆ×ιθ

```

Multiply the current item by each prime and loop over the products.

```
Ｆ›‹κη№υκ

```

Check whether the product is a new value.

```
⊞υκ

```

If so then push it to the list.

```
Ｉυ

```

Print the list.

# Answer
> 0 votes
# Pyth, 10 bytes

```
f!-PThQtUe

```

Try it online!

Takes input as `[[primes...], n]`

```
        Ue  # range(0, Q[-1])  (Q is the input, implicit)
       t    #                [1:] -> range(1, Q[-1]), tUe == PSe
f           # filter that on the condition: lambda T:
   PT       # prime_divisors(T)
  -  hQ     #                   - Q[0]
 !          # logical negation (![] == True)

```

# Answer
> 0 votes
# Perl 6, 27 bytes

```
{grep [*](@^a)**$^b%%*,^$b}

```

Try it online!

Port of xnor's Haskell solution. Also outputs 1.

# Answer
> 0 votes
# C (clang), 115 bytes

```
#define f(n,l,z){int j,i,k,x[n]={};for(i=x[1]=1;i<n;printf(x[i]+"\0%d ",i++))for(j=z;j--;k<n?x[k]=x[i]:0)k=i*l[j];}

```

Try it online!

A Sieve of Eratosthenes based solution.

(Includes 1 in the output)

Thanks to @ceilingcat suggestion : printf(x\[i\]+"\0%d ",i++) instead of x\[i\]&&printf("%d ",i),i++ I suppose it shifts the pointer of the literal but didn't found any documentation, if anyone can give me some insights it would be welcome.

# Answer
> 0 votes
# Husk, 8 bytes

```
fȯ¦⁰upŀ²

```

Try it online!

---
Tags: code-golf, primes
---


title: Calculate Swatch Internet Time

text:
# Question
Title: Calculate Swatch Internet Time
Output the **current time of day** as Swatch Internet Time.

Specifically, output a three-digit (zero-padded) number of ".beats" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").

For example, if the current time in UTC is `23:47`, then it is `00:47` in UTC+1 ("Biel Meantime"), and the output would be `032`.

**Examples**:

```
UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651

```

The program should produce this output then immediately exit.

Output is to standard output (or equivalent). **Must be a complete, runnable program, not a function.** The program takes no input; it outputs the *current* time.

# Answer
# PHP, 12 bytes

```
<?=@date(B);

```

But it can only be so short because PHP has built-in Swatch Internet Time support. So this answer isn't much fun.

---

`<?=` exits HTML mode and evaluates an expression, then echoes it.

`@` silences an error.

`date()` outputs the current time, formatting it with a given format string.

`B` is an undefined constant. In PHP, if you reference a constant that doesn't exist, you get back a string containing its name, and it also produces a “notice”-level error. Here, the `@` suppresses that error. `B` is the `date()` format code for Swatch Internet Time.

`;` terminates the expression.

---

If we assume PHP is being run with the default error-reporting settings, where “notices” are silenced, we could skip the `@`, and it would only be 11 bytes.
> 6 votes

# Answer
# C, *56 bytes*

```
main(){printf("%03d",(int)((time(0)+3600)%86400/86.4));}

```
Explanation: * **%03d** \- tells printf to zero-pad up to 3 digits.
* **time(NULL)+3600** \- gets amount of seconds (UTC) elapsed since epoch and adds an hour to it (UTC+1).
* **%86400** \- divides epoch by the amount of seconds in a 24hr day and gets the remainder (representing seconds elapsed, so far, "today").
* **/86.4** \- divide remaining seconds by 86.4 to get the ".beat" count since midnight (UTC+1).

### Compile (MSVC):

C:\> cl swatch.c

### Compile (GCC):

$ gcc swatch.c
> 5 votes

# Answer
# PHP, ~~48~~ 46 bytes

```
<?=sprintf("%03d",((time()+3600)%86400)/86.4);

```

I have another PHP answer above, but this one avoids using PHP's built-in Swatch Internet Time support, so it's more interesting, if longer.

This is largely self-explanatory if you're familiar with UNIX time and `sprintf`, ~~though note I'm using `|0` as a short way to truncate a float to an integer~~ (actually I realised this is unnecessary in PHP, oops!)
> 3 votes

# Answer
# Java 8, 143 bytes

```
import java.time.*;interface A{static void main(String[]a){System.out.format("%03.0f",LocalTime.now(ZoneId.of("UT+1")).toSecondOfDay()/86.4);}}

```

this uses Java 8's java.time package to get current time, convert it to UTC+1, and then get the number of seconds. At the end it divides by the number of 1000s of seconds in a day, which turns out to be 86.4.

Funny how the function that actually calculates the time is only about a third of the overall program size.
> 2 votes

# Answer
# Javascript, ~~53~~ ~~52~~ 48 bytes

```
alert((new Date/864e5%1+1/24+'0000').slice(2,5))

```

Explanation:

`new Date/864e5%1` is the fraction of a day in UTC. `+1/24` adds 1/24th of a day (1 hour), moving it to UTC+1.

`"0000"` is concatenated with this, turning it into a string. Then the 3rd through 5th characters are taken. The reason `"0000"` is concatenated instead of an empty string is for the cases in which there are fewer than 3 decimal places:

* `"0.XXX`(any number of digits here)`0000"` Swatch time is XXX
* `"0.XX0000"` Swatch time is XX0
* `"0.X0000"` Swatch time is X00
* `"00000"` Swatch time is 000

(the first character is 1 instead of 0 from 23:00 UTC to 24:00 UTC, but the first character is ignored.)
> 2 votes

# Answer
# 05AB1E, ~~29~~ 21 bytes

```
ža>60©%®*žb+₄*1440÷Dg3s-Å0š˜J

```

After compressing integers thanks to @KevinCruijssen (-8 bytes) :

```
ža>60©%®*žb+₄*Ž5¦÷₄+¦

```

Explanation:

```
ža>60©%®*žb+₄*1440÷Dg3s-Å0š˜J
ža                               push current hours in UT
  >                              increment
   60©                           push 60 and save in register c
      %                          hours mod 60
       ®*                        push from register c and Multiply
         žb+                     add current minutes
            ₄*                   multiply by 1000
              1440÷              Integer division with 1440
                   D             Duplicate
                    g            Length
                     3s-         3-length
                        Å0       create list of a 0s
                          š      Prepand
                           ˜J    Flat and joon

```

I didn't find a better idea for prepanding Zeros, so if anyone got a better idea I'll be glad to know :)

Try it online!

Try the 21 bytes online!
> 2 votes

# Answer
# JavaScript, 98 bytes

```
d=new Date();t=;console.log(Math.floor((360*d.getHours()+60*d.getMinutes()+d.getSeconds())/86.4));

```

Definitely could be optimized, I had some problems with the `Date` object so I'm looking into shorter ways to do that.
> 1 votes

# Answer
# Octave, 64 bytes

```
t=gmtime(time);sprintf("%03.f",(mod(++t.hour,24)*60+t.min)/1.44)

```

Uses veganaiZe's `printf` formatting.

I'm having a bit of difficulty with the time that ideone is returning, so here's a sample run with the time struct returned by `gmtime` for reference. I'll look around and see if I can get any of the other online Octave compilers to give me proper time.

```
t =
  scalar structure containing the fields:
    usec =  528182
    sec =  17
    min =  24
    hour =  21
    mday =  15
    mon =  6
    year =  116
    wday =  5
    yday =  196
    isdst = 0
    zone = UTC

ans = 933

```
> 1 votes

# Answer
# Python 2.7, ~~131~~ ~~128~~ 121 bytes:

```
from datetime import*;S=lambda f:int(datetime.utcnow().strftime(f));print'%03.0f'%(((S('%H')+1%24)*3600+S('%M')*60)/86.4)

```

A full program that outputs the Swatch Internet Time.

Simply uses Python's built in `datetime` module to first get the `UTC+0` time in hours and minutes using `datetime.utfnow().strftime('%H')` and `datetime.utfnow().strftime('%M')`, respectively. Then, the time is converted into `UTC+1` by adding `1` to the hours and then modding the sum by `24` to ensure the result is in the 24-hour range. Finally, the hour is turned into its equivalent in seconds, which is added to the minute's equivalent in seconds, and the resulting sum is divided by `86.4`, as there are `86.4` seconds or `1 min. 24 sec.` in 1 ".beat", after which, using string formatting, the quotient is rounded to the nearest integer and padded with zeroes until the length is `3`.

---

However, I am not the one to stop here. In the above solution, I used a more direct method to convert the time to `UTC+1`. However, wanted to add a bit of a bigger challenge for myself and implement this using *only* Python's built in `time` module, which apparently does *not* have any built-in method that I know of to convert local time into `UTC+0` time. So now, without further ado, here is the perfectly working version using *only* the time module, currently standing at **125 bytes**:

```
from time import*;I=lambda g:int(strftime(g));print'%03.0f'%((((I('%H')+1-daylight)%24*3600+timezone)%86400+I('%M')*60)/86.4)

```

This can output the correct Swatch Internet Time for *any and all* time zones, and basically does pretty much everything the same as in the first solution, except this time converts the local time into `UTC+1` by first adding `1` to the hour, and then subtracting `1` if daylight-savings time is currently, locally observed, or `0` otherwise. Then, this difference is modded by `24` to ensure that the result stays within the `24` hour range, after which it is multiplied by `3600` for conversion into seconds. This product is then added to the result from the built-in `timezone` method, which returns the local offset from `UTC+0`. After this, you finally have your hours in `UTC+1`. This then continues on from here as in the first solution.
> 1 votes

# Answer
# q/k (21 bytes)

```
7h$1e3*(.z.n+0D01)%1D

```
> 1 votes

# Answer
# Javascript, 83 bytes

```
a=(((36e5+(+new Date()))%864e5)/864e2).toFixed(),alert("00".slice(Math.log10(a))+a)

```
> 1 votes

# Answer
# CJam, 34 bytes

Update: I shouldn't code hungry. My previous answer was shorter, but didn't cast to int or left-pad. These are now fixed, with +8 bytes to left-pad (probably improvable), +1 to int cast, and -2 to optimizations. My old comment no longer applies.

```
r':/~\~)24md60*@~+1.44/i"%03d"e%o;

```

Try it online

Explanation:

```
r                   read input
 ':/                split on :
    ~               unwrap array
     \~             evaluate hour to numbers
       )            increment hour
        24md        modulo 24
            60*     multiply by 60
               @~   switch to minute and eval to num
+                   add hour*60 and minute
 1.44/              divide by 1.44 to get SIT
      i             cast to int
       "%03d"e%     format as 3 leading 0s
               o;   output and discard spare 0 from modulo

```
> 1 votes

# Answer
# Japt, <sup>~~27 23 19~~</sup> 15 bytes

```
Kj z86400 s t3n

```

Test it

Javascript port.

I hope I've done it correctly.

-4 bytes from Shaggy.

-4 more bytes from Shaggy.

-4 more more bytes from Shaggy.
> 1 votes

# Answer
# Python 3, 64 bytes

```
import time
t=time.gmtime()
print(int(-~t[3]%24/.024+t[4]/1.44))

```

Try it online!
> 1 votes

# Answer
# C#, 112 bytes

```
class P{static void M(){System.Console.Write((int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4));}}

```

---

# C#, 68 bytes

```
()=>(int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4);

```

A simple port of @veganaiZe's code. Thanks to him :)

Try it online!
> 0 votes

# Answer
## Common Lisp (Lispworks), 144 bytes

```
(defun f(s)(let*((d(split-sequence":"s))(h(parse-integer(first d)))(m(parse-integer(second d))))(round(/(+(*(mod(1+ h) 24)3600)(* m 60))86.4))))

```

ungolfed:

```
    (defun f (s)
      (let* ((d (split-sequence ":" s))
             (h (parse-integer (first d)))
             (m (parse-integer (second d))))
        (round
         (/
          (+
           (*
            (mod (1+ h) 24)
            3600)
           (* m 60))
          86.4))))

```

usage:

```
CL-USER 2759 > (f "23:47")
33
-0.36111111111111427

```
> 0 votes

---
Tags: code-golf, date
---


title: Parse a Scala expression

text:
# Question
Title: Parse a Scala expression
Scala isn't a very commonly used language around here. Most of those who know it like it<sup>\[citation needed\]</sup>, but some go `:\` when they encounter its user-defined operators, saying they're too complicated.

However, they're governed by a very simple set of rules, outlined here. Their precedence depends on the first character. Here's the list for that (highest to lowest precedence):

```
* / %
+ -
:
= !
< >
&
^
|
(all letters)

```

So this

```
a + b ^? c less a ==> b | c

```

would be the same as this

```
((a + b) ^? c) less ((a ==> b) | c)

```

Your task is to turn such an expression (only infix applications) into a tree-like structure or a string with all the sub-expressions in parentheses.

## Input

A string or multiple characters given as an argument to a function, read from STDIN, given as command-line arguments, or using one of the other default input methods. This string is the expression to be parsed.

## Output

You could do one of the following, printed to STDOUT, returned from a function, or one of the other default output methods:

* The same string but with parentheses outside each sub-expression (the outermost expression may or may not be parenthesized). E.g., `expr op expr2 op2 expr3` -\> `(expr op expr2) op2 expr3`. If you wish, you may also parenthesize the atoms (`(((expr) op (expr2)) op2 (expr3))`)
* A multidimensional list, where each expression would broken up into the left argument, the operator/method, and the right argument. E.g., `expr op expr2 op2 expr3` -\> `[['expr','op','expr2'],'op2','expr3']`
* Some tree-like structure equivalent to the above 2 representations. You get the idea.

## Rules

* All operators used are binary, infix, and left-associative.
* Parsing goes from left to right.
* There will always be one or more spaces between arguments and operators.
* Operators may consist of any of the symbols mentioned above (`*/%+-:=!<>&^|`) and uppercase or lowercase letters(`[A-Za-z]`). They will be one or more characters.
* Arguments to methods may be other expressions or alphabetical identifiers (`[A-Za-z]`).
* This is , so shortest code wins!

## Test cases

More coming soon

```
Input                             -> Output
a -- blah /\ foo                  -> a -- (blah /\ foo)
same ** fst *^ chr *& operators   -> ((same ** fst) *^ chr) *& operators
Lots   Of     SpAceS // here      -> Lots Of (SpAceS // here)
Not : confusing * At / ALL iS it  -> (Not : ((confusing * At) / ALL)) iS it
This *isnot* valid ** Scala       -> (This *isnot* valid) ** Scala

```

# Answer
> 4 votes
# JavaScript (ES6),  ~~180 ... 155~~  152 bytes

Returns a multidimensional list. The outermost expression is parenthesized, and so are the atoms.

```
f=(i,a=i.split(/ +/))=>"w | ^ & <> =! : +- */%".split` `.some(p=>a.map((s,j)=>i=!!s.match(`^[\\${p}]`)&j?j:i)|i)?[f(i=a.splice(i),a),i.shift(),f(a,i)]:a

```

Try it online!

### How?

This is a recursive algorithm. At each iteration, we look for the **last operator** with the **lowest precedence**, split the expression at this position and process recursive calls on both resulting parts. We stop the recursion when we reach an atom.

In order to split the expression and isolate the operator, we use a combination of `splice()` and `shift()` as shown in the following example, where integers are used instead of operators and operands.

```
a = [ 0, 1, 2, 3, 4, 5, 6 ];
i = 3;
i = a.splice(i); // --> a[] = [ 0, 1, 2 ] (left expression)
                 //     i[] = [ 3, 4, 5, 6 ] (operator + right expression)
i.shift();       // --> operator = 3
                 //     i[] = [ 4, 5, 6 ] (right expression)

```

### Commented

```
f = (                      // f is a recursive function taking:
  i,                       //   i   = input string on the 1st iteration,
                           //         and then some non-empty array
  a = i.split(/ +/)        //   a[] = input string split on spaces
) =>                       //         NB: operators are expected at odd positions
  "w | ^ & <> =! : +- */%" // this string describes the groups of operators,
                           // from lowest to highest precedence
  .split` `                // split it
  .some(p =>               // for each pattern p:
    a.map((s, j) =>        //   for each string s at position j in a[]:
      i =                  //     update i:
        !!s.match(         //       see if s matches p; the '\' is required for
          `^[\\${p}]`      //       'w' and '^', and harmless for the other ones
        ) & j ?            //       if there's a match and j is odd:
          j                //         update i to j
        :                  //       else:
          i                //         leave i unchanged
    )                      //   end of map()
    | i                    //   make some() succeed if i is a number
  ) ?                      // end of some(); if successful:
    [                      //   build a new array consisting of:
      f(                   //     the result of a recursive call ...
        i = a.splice(i), a //     ... with the left expression
      ),                   //
      i.shift(),           //     followed by the operator
      f(                   //     followed by the result of a recursive call ...
        a, i               //     ... with the right expression
      )                    //
    ]                      //   end of new array
  :                        // else:
    a                      //   just return a[]

```

# Answer
> 4 votes
# Jelly, 59 bytes

```
Ḳ¹ƇµḊm2ZḢeⱮ€ØẠṭ“*/%“+-“:“=!“<>“&“^“|”¤i€1ỤḢḤ+-,2œṖ⁸W€2¦ẎµÐL

```

A monadic Link accepting a list of characters which yields a list containing the bracketed expression as nested lists of `[expr, op, expr]` where `expr` and `op` are lists of characters.

**Try it online!**

### How?

```
Ḳ¹Ƈµ...µÐL - Link: list of characters, E
Ḳ          - split at spaces
  Ƈ        - keep those which are truthy under:
 ¹         -   identity (falsey for empty lists)
   µ...µÐL - repeat the monadic link (below) until no change occurs

Ḋm2ZḢeⱮ€ØẠṭ“...”¤i€1ỤḢ - link, wrap three at highest precedence operator: list
Ḋ                      - deueue
 m2                    - mod-2 slice -> gets operators
   Z                   - transpose
    Ḣ                  - head -> first characters of operators
                ¤      - nilad followed by link(s) as a nilad:
        ØẠ             -   letters "A..Za..z"
           “...”       -   ["*/%","+-",":","=!","<>","&","^","|"]
          ṭ            -   tack -> ["*/%","+-",":","=!","<>","&","^","|","A..Za..z"]
       €               - for each (1st character):
      Ɱ                -   map accross (the lists of characters) with:
     e                 -     exists in?
                 i€1   - first (1-based) index of 1 in each (0 if no 1 found)
                    Ụ  - grade-up (list of 1-based indices sorted by value)
                     Ḣ - head
                       - continued below...

Ḥ+-,2œṖ⁸W€2¦Ẏ          - ...continued
Ḥ                      - double -> index, I, of operator in original list
  -,2                  - [-1,2]
 +                     - add -> [I-1, I+2]
       ⁸               - chain's left argument, the list
     œṖ                - partition (the list) at indices ([I-1, I+2])
         €2¦           - apply to the secod element (the [expr, op, expr])
        W              - wrap in a list
            Ẏ          - tighten

```

# Answer
> 3 votes
# Retina, 111 bytes

```
,2,`\S+
{$&}
~(K`*/%¶-+¶:¶!=¶<>¶&¶\^¶|¶\w
)L$`.+
+0`{([^{}]+)}( +[$&][^ {}]$* +){([^{}]+)}¶{($$1)$$2($$3)}
{|}

```

Try it online! Link includes test cases and a parenthesis-removing footer. Explanation:

```
,2,`\S+
{$&}

```

Wrap only the variables in braces.

```
~(
)

```

Evaluate the enclosed stages and execute the result as a script on the wrapped input.

```
K`*/%¶-+¶:¶!=¶<>¶&¶\^¶|¶\w

```

Temporarily replace the input with a list of character classes. Note that -+ in particular is in that order because of the way character classes work. The character classes are listed in descending order of priority.

```
L$`.+

```

Loop over each character class in the list.

```
+0`{([^{}]+)}( +[$&][^ {}]$* +){([^{}]+)}¶{($$1)$$2($$3)}

```

Find the first operator beginning with that class, wrap its parameters in parentheses, and wrap the subexpression in braces.

```
{|}

```

Remove the now enclosing braces.

The actual generated code looks like this:

```
+0`{([^{}]+)}( +[\w][^ {}]* +){([^{}]+)}

```

Match a braced term, then the operator, then another braced term.

```
{($1)$4($5)}

```

Wrap the terms on both sides of the operator in parentheses, and wrap the subexpression in braces.

Previous 126-byte version accepted any character not one of space, parentheses or previously defined operator character as an operator of the highest precedence:

```
.+
($&)
~(K`a-z¶|¶\^¶&¶<>¶!=¶:¶-+¶*/%¶^ ()
L$`.+
+0i`\(((([^ ()]+ +){2})$*[^ ()]+)( +[$&][^ ()]$* +)([^()]+)\)¶(($$1)$$4($$5))

```

Try it online! Link includes test cases and a parenthesis-removing footer. Explanation:

```
.+
($&)

```

Wrap the entire expression in parentheses.

```
~(

```

Evaluate the remaining stages and execute the result as a script on the wrapped input.

```
K`a-z¶|¶\^¶&¶<>¶!=¶:¶-+¶*/%¶^ ()

```

Temporarily replace the input with a list of character classes. Note that `-+` in particular is in that order because of the way character classes work. The character classes are listed in ascending order of priority.

```
L$`.+

```

Loop over each character class in the list.

```
+0i`\(((([^ ()]+ +){2})$*[^ ()]+)( +[$&][^ ()]$* +)([^()]+)\)¶(($$1)$$4($$5))

```

Find the largest possible sub expression that contains an operator beginning with that class and wrap both of the arguments in parentheses.

The actual generated code looks like this:

```
+0i`\(((([^ ()]+ +){2})*[^ ()]+)( +[a-z][^ ()]* +)([^()]+)\)

```

Match a `(`, then an even number of terms, then a term, then the operator, then any remaining terms, then a `)`.

```
(($1)$4($5))

```

Wrap the terms on both sides of the operator in parentheses.

# Answer
> 3 votes
# Perl 5, ~~292~~ ~~149~~ 137 bytes

(last 12 bytes lost with tip from Nahuel Fouilleul in comments below)

```
sub{$_=pop;s/ +/ /g;for$o(qw(\*\/% +- : =! <> & \^ | \w)){1while s/\S+ +[$o]\S* +\S+/push@s,$&;"$#s,"/e}1while s/\d+,/($s[$&])/;/.(.*)./}

```

Try it online!

```
sub {
  $_=pop;                             #put input string in $_
  s/ +/ /g;                           #trim away unneeded spaces
  for $o (                            #loop through operators
    qw(\*\/% +- : =! <> & \^ | \w)    #...in order of precedence
  ) {
    1 while s/\S+\s+[$o]\S*\s+\S+     #find first such operator and
             /push@s,$&; "$#s,"       #replace its sub-expression with
             /ex                      #a tag of id plus comma
                                      #and continue until no more
                                      #of current operator
  }
  1 while s/\d+,/($s[$&])/;           #replace all tags with their
                                      #subexpressions, now in parens
  /.(.*)./                            #remove first+last char, return rest
}

```

# Answer
> 3 votes
# Charcoal, ~~82~~ ~~68~~ 67 bytes

```
≔⮌Φ⪪Ｓ ιθＦ⪪⁺“ ∨μ[Ek✂◧‽_U⁹�A\”α.«Ｗ⊖Ｌθ¿№ι↥§§θ⊖κ⁰⊞θＥ³⊟θＦ²⊞υ⊟θＷυ⊞θ⊟υ»⭆θι

```

Try it online! Link is to verbose version of code. Outputs the Python representation of a nested list. Explanation:

```
≔⮌Φ⪪Ｓ ιθ

```

Split the input string on spaces and filter out empty strings (corresponding to runs of spaces). Reverse the result, so that the list can be processed by popping terms from it.

```
Ｆ⪪⁺“ ∨μ[Ek✂◧‽_U⁹�A\”α.«

```

Concatenate the compressed literal string `*/%.-+.:.!=.<>.&.^.|.` with the uppercase alphabet, split on `.`s, and loop over each character class.

```
Ｗ⊖Ｌθ

```

While there are operators left to process:

```
¿№ι↥§§θ⊖κ⁰

```

Does the uppercased current operator start with a character in the current class?

```
⊞θＥ³⊟θ

```

If so then extract the operator and its parameters into their own sublist, and then push that list back as the left parameter of the next operator.

```
Ｆ²⊞υ⊟θ

```

Otherwise move the operator and its left parameter to a temporary list.

```
Ｗυ⊞θ⊟υ

```

Once all of the operators have been processed move all the saved operators and parameters back to the main list, also emptying the temporary list again.

```
»⭆θι

```

Stringify the resulting list.

~~85~~ 70 bytes for a human-readable format (with enclosing parentheses):

```
≔⮌Φ⪪Ｓ ιθＦ⪪⁺“ ∨μ[Ek✂◧‽_U⁹�A\”α.«Ｗ⊖Ｌθ¿№ι↥§§θ⊖κ⁰⊞θ⪫()⪫Ｅ³⊟θ Ｆ²⊞υ⊟θＷυ⊞θ⊟υ»θ

```

Try it online! Link is to verbose version of code. Explanation: As above, but after extracting the three elements into an array, the array is joined with spaces and then wrapped in parentheses before being pushed back to the list, meaning that the final result can be directly printed.

# Answer
> 3 votes
# Scala, 308 bytes

I am sure it is not the shortest way to do that, but here is a solution in Scala :)

```
s=>{def g(q:Seq[String]):String=if(q.size<2)q(0)else{val o=Seq("*/%","+-",":","!=","<>","&","^","|").zipWithIndex
val t=1.to(q.size-1,2).map(r=>o.map(a=>(r,if(a._1.contains(q(r)(0)))a._2 else 8))).map(_.minBy(_._2)).reverse.maxBy(_._2)._1
"("+g(q.take(t))+")"+q(t)+"("+g(q.drop(t+1))+")"}
g(s.split("\\s+"))}

```

Try it online!

---
Tags: code-golf, string, parsing, scala
---


title: Draw a regular polygon

text:
# Question
Title: Draw a regular polygon
The goal of this code golf is to draw a regular polygon (one with equal side lengths) given the number of sides and radius (distance from center to vertex).

* The number of sides and the radius can be entered via a file, STDIN, or just a plain old variable. Use whatever is shorter in your language.
* -25% of total characters/bytes if the image is actually drawn instead of ASCII art.

# Answer
> 21 votes
**LOGO 37 - 25% = 27.75 (with variables)**

```
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

```

**LOGO 49 - 25% = 36.75 (as a function)**

```
TO P:R:S REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]END

```

**Triangle**

*Called with variables*

```
Make "R 100
Make "S 3
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

```

*Used as a function* `P 100 3`

**Square**

*Called with variables*

```
Make "R 100
Make "S 4
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

```

*Used as a function* `P 100 4`

**Pentagon**

*Called with variables*

```
Make "R 100
Make "S 5
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

```

*Used as a function* `P 100 5`

**Decagon**

*Called with variables*

```
Make "R 100
Make "S 10
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

```

*Used as a function* `P 100 10`

**Circle**

*Called with variables*

```
Make "R 100
Make "S 360
REPEAT:S[FD:R*2*sin(180/:S)RT 360/:S]

```

*Used as a function* `P 100 360`

# Answer
> 17 votes
## Mathematica, 40 - 25% = 30

```
ListPolarPlot[r&~Array~n]/.PointPolygon

```

# Answer
> 12 votes
## Java 8 : ~~533~~ 322 - 25% = 241.5

Well, it's Java :/ Just draws lines, point to point. Should work for any arbitrarily sized polygon. Cut it down quite a bit from original size. Huge credit to Vulcan (in comments) for the golf lesson.

```
import java.awt.*;class D{public static void main(String[]v){new Frame(){public void paint(Graphics g){int i=0,r=Short.valueOf(v[0]),s=Short.valueOf(v[1]),o=r+30,x[]=new int[s],y[]=x.clone();for(setSize(o*2,o*2);i<s;x[i]=(int)(Math.cos(6.28*i/s)*r+o),y[i]=(int)(Math.sin(6.28*i++/s)*r+o));g.drawPolygon(x,y,s);}}.show();}}

```

Line Breaks:

```
import java.awt.*;
class D{
    public static void main(String[]v){
        new Frame(){
            public void paint(Graphics g){
                int i=0,r=Short.valueOf(v[0]),s=Short.valueOf(v[1]),o=r+30,x[]=new int[s],y[]=x.clone();
                for(setSize(o*2,o*2);i<s;x[i]=(int)(Math.cos(6.28*i/s)*r+o),y[i]=(int)(Math.sin(6.28*i++/s)*r+o));
                g.drawPolygon(x,y,s);
            }
        }.show();
    }
}

```

Input is arguments \[radius\] \[sides\]:

```
java D 300 7

```

Output:

# Answer
> 11 votes
# TeX/TikZ (60 – 80.25)

File `polygon.tex`:

```
\input tikz \tikz\draw(0:\r)\foreach\!in{1,...,\n}{--(\!*360/\n:\r)}--cycle;\bye

```

(80 bytes)

The radius and number of sides are provided as variables/macros `\r` and `\n`. Any TeX unit can be given for the radius. Without unit, the default unit `cm` is used. Examples:

```
\def\r{1}\def\n{5}    % pentagon with radius 1cm
\def\r{10mm}\def\n{8} % octagon with radius 10mm

```

(16 bytes without values)

If the page number should be suppressed, then it can be done by

```
\footline{}

```

(11 bytes)

Examples for generating PDF files:

```
pdftex "\def\r{1}\def\n{3}\input polygon"

```

>

```
pdftex "\def\r{1}\def\n{5}\input polygon"

```

>

```
pdftex "\def\r{1}\def\n{8}\input polygon"

```

>

```
pdftex "\def\r{1}\def\n{12}\input polygon"

```

>

**Score:**

It is not clear to, what needs counting. The range for the score would be:

* The base code is 80 bytes minus 25% = **60**
* Or all inclusive (input variable definitions, no page number): (80 + 16 + 11) minus 25% = **80.25**
* If the connection between the first and last point do not need to be smooth, then `--cycle` could be removed, saving 7 bytes.

# Answer
> 8 votes
## Geogebra, 42 – 25% = 31.5 bytes

If you count in characters instead of bytes, this would be 41 – 25% = 30.75 characters.

(That is, if you consider Geogebra a language...)

Assumes the radius is stored in the variable `r` and the number of sides stored in the variable `s`.

```
Polygon[(0,0),(sqrt(2-2cos(2π/s))r,0),s]

```

This uses the cosine theorem *c*2 = *a*2 \+ *b*2 – 2 *a b* cos *C* to calculate the side length from the given radius.

Sample output for `s`=7, `r`=5

# Answer
> 6 votes
# C, 359 Chars

My first attempt at golfing. At least it beats the Java solution ;-)

```
int r,n,l,g,i,j,x,y;char* b;float a,c,u,z,p,q,s,t;main(int j,char**v){r=atoi(v[1]);b=malloc(g=(l=r*2+1)*r*2+1);memset(b,32,g);for(j=g-2;j>0;j-=l){b[j]='\n';}b[g-1]=0;a=2*3.14/(n=atoi(v[2]));for(;i<=n;i++,p=s,q=t){c=i*a;s=sin(c)*r+r;t=cos(c)*r+r;if(i>0){u=(s-p)/r,z=(t-q)/r;for(j=0;j<r;j++){x=p+u*j;y=q+z*j;if(x>=0&&y>=0&&y<r*2&&x<l-1)b[y*l+x]='#';}}}puts(b);}

```

ungolfed:

```
int r,n,l,g,i,j,x,y;
char* b;
float a,c,u,z,p,q,s,t;
main(int j,char**v){
    r=atoi(v[1]);
    b=malloc(g=(l=r*2+1)*r*2+1);
    memset(b,32,g);
    for(j=g-2;j>0;j-=l){b[j]='\n';}
    b[g-1]=0;
    a=2*3.14/(n=atoi(v[2]));
    for(;i<=n;i++,p=s,q=t){
        c=i*a;s=sin(c)*r+r;t=cos(c)*r+r;
        if(i>0){
            u=(s-p)/r,z=(t-q)/r;
            for(j=0;j<r;j++){
                x=p+u*j;y=q+z*j;
                if(x>=0&&y>=0&&y<r*2&&x<l-1)b[y*l+x]='#';
            }
        }
    }
    puts(b);
}

```

And it's the only program that outputs the polygon in ASCII instead of drawing it. Because of this and some floating point rounding issues, the output doesn't look particularly pretty (ASCII Chars are not as high as wide).

```
                 ######
               ###    ###
            ####        ####
          ###              ###
        ###                  ####
     ###                        ###
     #                            #
     #                            ##
    #                              #
    #                              #
   ##                              ##
   #                                #
  ##                                ##
  #                                  #
  #                                  #
 ##                                  ##
 #                                    #
##                                    ##
#                                      #
#                                      #
#                                      #
#                                      #
##                                    ##
 #                                    #
 ##                                  ##
  #                                  #
  #                                  #
  ##                                ##
   #                                #
   ##                              ##
    #                              #
    #                              #
     #                            ##
     #                            #
     ###                        ###
        ###                  ####
          ###              ###
            ###         ####
               ###    ###
                 ######

```

# Answer
> 6 votes
# C: 229 180

```
#include<stdio.h>
#include<math.h>
main(){float n=5,r=10,s=tan(1.57*(1.-(n-2.)/n))*r*2.,i=0,j,x,c,t;int u,v;for(;i<n;i++)for(j=0;j<s;j++)x=i*6.28/n,c=cos(x),t=sin(x),x=j-s/2.,u=c*r+t*x+r*2.,v=-t*r+c*x+r*2,printf("\e[%d;%dH*",v,u);}

```

(r is radius of incircle)

Please run in ANSI terminal

### Edit:

* take ace's suggestion
* use old variables (or #define) as input
* use circumcircle radius now

```
u;main(v){float p=3.14,r=R*cos(p/n),s=tan(p/n)*r*2,i=0,j,x,c,t;for(;i++<n;)for(j=0;j<s;)x=i*p/n*2,c=cos(x),t=sin(x),x=j++-s/2,u=c*r+t*x+r*2,v=c*x-t*r+r*2,printf("\e[%d;%dH*",v,u);}

```

compile:

```
gcc -opoly poly.c -Dn=sides -DR=radius -lm

```

# Answer
> 4 votes
## Mathematica, 54 * 75% = 40.5

```
Graphics@Polygon@Table[r{Cos@t,Sin@t},{t,0,2Pi,2Pi/n}]

```

I don't even think there's a point for an ungolfed version. It would only contain more whitespace.

Expects the radius in variable `r` and number of sides in variable `n`. The radius is a bit meaningless without displaying axes, because Mathematica scales all images to fit.

Example usage:

# Answer
> 4 votes
# HTML/JavaScript : ~~215 - 25% = 161.25~~, 212 - 25% = 159

```
<canvas><script>R=100;i=S=10;c=document.currentScript.parentNode;c.width=c.height=R*2;M=Math;with(c.getContext("2d")){moveTo(R*2,R);for(;i-->0;){a=M.PI*2*(i/S);lineTo(R+M.cos(a)*R,R+M.sin(a)*R)}stroke()}</script>

```

Ungolfed version :

```
<canvas><script>
    var RADIUS = 100;
    var SIDES_COUNT = 10;
    var canvas = document.currentScript.parentNode;
    canvas.width = canvas.height = RADIUS * 2;
    var context = canvas.getContext("2d");
    context.moveTo(RADIUS * 2, RADIUS);
    for(i = 1 ; i <= SIDES_COUNT ; i++) {
        var angle = Math.PI * 2 * (i / SIDES_COUNT);
        context.lineTo(
            RADIUS + Math.cos(angle) * RADIUS,
            RADIUS + Math.sin(angle) * RADIUS
        );
    }
    context.stroke();
</script>

```

# Answer
> 3 votes
## Postscript 156 - 25% = 117

```
translate exch 1 exch dup dup scale div currentlinewidth mul setlinewidth
1 0 moveto dup{360 1 index div rotate 1 0 lineto}repeat closepath stroke showpage

```

Pass the radius, number of sides, and center point on the command line

```
gs -c "100 9 300 200" -- polyg.ps

```

or prepend to the source

```
echo 100 9 300 200 | cat - polyg.ps | gs -

```

Translate to the center, scale up to the radius, move to (1,0); then repeat n times: rotate by 360/n, draw line to (1,0); draw final line, stroke and emit the page.

# Answer
> 3 votes
## Sage, 44 - 25% = 33

Assumes the number of sides is stored in the `s` variable and the radius is stored in the `r` variable.

```
polytopes.regular_polygon(s).show(figsize=r)

```

Sample output:

`s`=5, `r`=3

`s`=5, `r`=6

`s`=12, `r`=5

# Answer
> 3 votes
# bc + ImageMagick + xview + bash, 104.25 (139 bytes - 25%)

This challenge would be incomplete without an ImageMagick answer...

```
convert -size $[$2*2]x$[$2*2] xc: -draw "polygon `bc -l<<Q
for(;i++<$1;){t=6.28*i/$1;print s(t)*$2+$2,",";c(t)*$2+$2}
Q`" png:-|xview stdin

```

For example, `./polygon.sh 8 100` produces this image:

# Answer
> 2 votes
**JavaScript 584 (867 ungolfed)**

This code uses N Complex Roots of unity and translates the angles to X,Y points. Then the origin is moved to centre of the canvas.

*Golfed*

```
function createPolygon(c,r,n){
c.width=3*r;
c.height=3*r;
var t=c.getContext("2d");
var m=c.width/2;
t.beginPath();
t.lineWidth="5";
t.strokeStyle="green";
var q=C(r, n);
var p=pts[0];
var a=p.X+m;
var b=p.Y+m;
t.moveTo(a,b);
for(var i=1;i<q.length;i++)
{
p=q[i];
t.lineTo(p.X+m,p.Y+m);
t.stroke();
}
t.lineTo(a,b);
t.stroke();
}
function P(x,y){
this.X=x;
this.Y=y;
}
function C(r,n){
var p=Math.PI;
var x,y,i;
var z=[];
var k=n;
var a;
for(i=0;i<k;i++)
{
a = 2*i*p/n;
x = r*Math.cos(a);
y = r*Math.sin(a);
z.push(new P(x,y));
}
return z;
}

```

Sample output:

*Ungolfed*

```
function createPolygon(c,r,n) {
c.width = 3*r;
c.height = 3*r;
var ctx=c.getContext("2d");
var mid = c.width/2;
ctx.beginPath();
ctx.lineWidth="5";
ctx.strokeStyle="green";
var pts = ComplexRootsN(r, n);
if(null===pts || pts.length===0)
{
alert("no roots!");
return;
}
var p=pts[0];
var x0 = p.X + mid;
var y0 = p.Y + mid;
ctx.moveTo(x0,y0);
for(var i=1;i<pts.length;i++)
{
p=pts[i];
console.log(p.X +"," + p.Y);
ctx.lineTo(p.X + mid, p.Y + mid);
ctx.stroke();
}
ctx.lineTo(x0,y0);
ctx.stroke();
}

function Point(x,y){
this.X=x;
this.Y=y;
}

function ComplexRootsN(r, n){
var pi = Math.PI;
var x,y,i;
var arr = [];
var k=n;
var theta;
for(i=0;i<k;i++)
{
theta = 2*i*pi/n;
console.log('theta: ' + theta);
x = r*Math.cos(theta);
y = r*Math.sin(theta);
console.log(x+","+y);
arr.push(new Point(x,y));
}
return arr;
}

```

This code requires HTML5 canvas element, c is canvas object, r is radius and n is # of sides.

# Answer
> 2 votes
## PHP 140 - 25% = 105

```
<?
for(;$i++<$p;$a[]=$r-cos($x)*$r)$a[]=$r-sin($x+=2*M_PI/$p)*$r;
imagepolygon($m=imagecreatetruecolor($r*=2,$r),$a,$p,0xFFFFFF);
imagepng($m);

```

Assumes two predefined variables: `$p` the number of points, and `$r` the radius in pixels. Alternatively, one could prepend `list(,$r,$p)=$argv;` and use command line arguments instead. Output will be a png, which should be piped to a file.

---

### Output

`$r=100; $p=5;`

`$r=100; $p=6;`

`$r=100; $p=7;`

`$r=100; $p=50;`

# Answer
> 2 votes
# HTML + JavaScript, 12 + 127 = 139 bytes

```
<canvas id=c

```

```
s=>r=>(g=n=>n?g(n-1,d.lineTo(r+r*M.cos(x=M.PI*2*n/s),r+r*M.sin(x))):d.fill())(s,c.width=c.height=r+r,d=c.getContext`2d`,M=Math)

```

Try it on Codepen

# HTML (SVG) + JavaScript, 20 + 140 = 160 bytes

```
<svg id=c><path id=p

```

```
s=>r=>p.setAttribute(`d`,`M${M=Math,v=c.style,v.width=v.height=r+r},`+r+(g=n=>n?`L${r+r*M.cos(x=M.PI*2*n/s)},`+(r+r*M.sin(x))+g(n-1):``)(s))

```

Try it on Codepen

# Answer
> 2 votes
# , 42 bytes -25% = 31.5

```
function(n,r,p=r*1i^(4/n*0:n))plot(p,,"l")

```

Try it at rdrr.io

Calculates coordinates of vertices in the complex plane as `r` times a power-series of the (4/n)th-root of `i`.

Example output of `regular_polygon(7,3)`:

# Answer
> 1 votes
# TI-80 BASIC, 25 bytes - 25% = 18.75

```
PARAM
2π/ANS->TSTEP
"COS T->X1ᴛ
"SIN T->Y1ᴛ
DISPGRAPH

```

Assumes all settings are set to the default values. Run the program like `5:PRGM_POLYGON` (for a pentagon)

It works by drawing a circle with a very low number of steps. For example, a pentagon would have steps of 2π/5 radians.

The window settings are good enough by default, and `TMIN` and `TMAX` are set to `0` and , so all we need to change is `TSTEP`.

# Answer
> 1 votes
# SmileBASIC 3, 183 159 - 25% = 119.25 bytes

Takes the sides and radius from `INPUT`, calculates and stores the points, and then draws them by using `GLINE`. I feel like this could be shorter but it's like 1 AM, whatever. Assumes a clean and default display env, so you might need to `ACLS` when running it from DIRECT.

```
INPUT S,R
DIM P[S,2]FOR I=0TO S-1
A=RAD(I/S*360)P[I,0]=COS(A)*R+200P[I,1]=SIN(A)*R+120NEXT
FOR I=0TO S-1GLINE P[I,0],P[I,1],P[(I+1)MOD S,0],P[(I+1)MOD S,1]NEXT

```

# Answer
> 1 votes
## OpenSCAD: 31 less 25% = 23.25

```
module p(n,r){circle(r,$fn=n);}

```

First post here! I know I'm late to the party, but this seemed like as good a question as any to start with. Call using `p(n,r)`.

# Answer
> 1 votes
## APL (dzaima/APL), ~~50 - 12.5 = 37.5~~ 37 - 9.25 = 27.75 bytes

```
P5.draw←{P5.G.ln ↑r+r×2 1○ᑈs÷⍨2×○0…s}

```

Shortened heavily with the help of The APL Orchard.

### Explanation:

```
P5.draw←{P5.G.ln ↑r+r×2 1○ᑈs÷⍨2×○0…s}
P5.draw←{                           } Draw the following on the canvas every frame:
         P5.G.ln                      Draw a line using array(x1,y1,x2,y2...)
                                 0…s  Range from 0 to number of sides
                              2×○     times 2π
                           s÷⍨        divided by number of sides
                      2 1○ᑈ           Take cos and sin of each of the values from the left
                 ↑r+r×                Multiply the list by r and add r to center it,
                                      then mix the values of the list together

```

Previous version:

```
p←(2×○⍳s+1)÷s
P5.draw←{P5.G.ln r+r×⍉(2○p)↑⍤⍮(1○p)}

```

Takes input as variables `r` and `s`, draws polygon with center at \\$(r,r)\\$.

Made with the help of the formula used here.

### Outputs:

`100 3`

`100 5`

`200 7`

To execute the program, use the setup here, for a full view of the drawn polygon.

# Answer
> 0 votes
## C# in LINQPAD

Credit for the math part goes to Geobits (I hope you don't mind!) with the Java answer. I'm *hopeless* at math :)

I did this in LINQPAD as it's got a built in output window. So essentially you can drag and drop the following in to it and it'll draw the polygon. Just switch it to 'C# Program', and import the System.Drawing lib into the query properties.

```
//using System.Drawing;

void Main()
{
// Usage: (sides, radius)
    DrawSomething(4, 50);
}

void DrawSomething(int sides, int radius)
{
    var points = new Point[sides];
    var bmpSize = radius*sides;
    var bmp = new Bitmap(bmpSize,bmpSize);
    using (Graphics g = Graphics.FromImage(bmp))
    {
        var o = radius+30;
        for(var i=0; i < points.Length; i++)
        {
            // math thanks to Geobits
            double w = Math.PI*2*i/sides;
            points[i].X = (int)(Math.Cos(w)*radius+o);
            points[i].Y = (int)(Math.Sin(w)*radius+o);
        }
        g.DrawPolygon(new Pen(Color.Red), points);
    }
    Console.Write(bmp);
}

```

# Answer
> 0 votes
**ActionScript 1, Flash Player 6: 92 - 25% = 69**

```
n=6
r=100
M=Math
P=M.PI*2
lineStyle(1)
moveTo(r,0)
while((t+=P/n)<=P)lineTo(M.cos(t)*r,M.sin(t)*r)

```

# Answer
> 0 votes
# Python 2, 74 bytes - 25% = 55.5

Input is in the variables `r,n`. If included in the count, it would be `r,n=input()`, for 12 bytes more.

```
import math,turtle as t
exec"t.fd(2*r*math.sin(180/n));t.rt(360/n);"*n

```

**Try it online** \- *(uses different code since `exec` is not implemented in the online interpreter)*

# Answer
> 0 votes
# Matlab 58 bytes - 25% = 43.5

Saw no Matlab solution, so here is one which is pretty straightforward:

```
f=@(n,r) plot(r*cos(0:2*pi/n:2*pi),r*sin(0:2*pi/n:2*pi));

```

You can shave off some bytes if **r** and **n** are already in the workspace.

Example call:

```
f(7,8)

```

# Answer
> 0 votes
# Python 2, 222 bytes

```
from math import*
def f(s,r):
 r*=cos(pi/s)
 v,R=2*pi/s,[(2*t)/98.-1for t in range(99)]
 print"P1 99 99 "+" ".join(["0","1"][all(w*(w-x)+z*(z-y)>0for w,z in[(r*cos(a*v),r*sin(a*v))for a in range(s)])]for x in R for y in R)

```

Checks if a pixel is on the inner side of all hyperplanes (lines) of the polygon. The radius is touched because actually the apothem is used.

# Answer
> 0 votes
# SmileBASIC, ~~85~~ 75 - 25% = 56.25 bytes

```
FOR I=0TO S
A=I/S*6.28N=X
M=Y
X=R+R*COS(A)Y=R+R*SIN(A)GLINE N,M,X,Y,-I
NEXT

```

Variables S and R are used for input.

Explained:

```
FOR I=0 TO Sides        'Draw n+1 sides (since 0 is skip)
 Angle=I/Sides*6.28     'Get angle in radians
 OldX=X:OldY=Y          'Store previous x/y values
 X=Radius+Radius*COS(A) 'Calculate x and y
 Y=Radius+Radius*SIN(A)
 GLINE OldX,OldY,X,Y,-I 'Draw line. Skip if I is 0 (since old x and y aren't set then)
NEXT

```

The sides are drawn using the color `-I`, which is usually close to -1 (&HFFFFFFFF white) (except when `I` is 0, when it's transparent).

You can also draw a filled polygon by using `GTRI N,M,X,Y,R,R,-I` instead of `GLINE...`

# Answer
> 0 votes
# Mathematica 27 ( = 36 - 25%)

```
Graphics[Polygon[CirclePoints[r, n]]]

```

When we submit Mathematica code we often forget about new functions that keep getting built into the language, with current language vocabulary amassing around 5000 core functions. Large and expanding language vocabulary is btw quite handy for code-golfing. CirclePoints were introduced in the current version 11.X. A specific example of 7-sided radius 5 is:

Also you just need to enter angle parameter to control orientation of your polygon:

```
Graphics[Polygon[CirclePoints[{1, 2}, 5]]]

```

# Answer
> 0 votes
# Tikz, 199 bytes

```
\documentclass[tikz]{standalone}\usetikzlibrary{shapes.geometric}\begin{document}\tikz{\def\p{regular polygo}\typein[\n]{}\typein[\r]{}\node[draw,minimum size=\r,\p n,\p n sides=\n]{}}\end{document}

```

This solution uses the tikz library `shapes.geometric`.

Here is what a polygon with `5` sides and radius `8in` looks like when viewed in evince.

# Answer
> 0 votes
# MATLAB/Octave, 26.25 bytes (35 bytes-25%)

```
@(n,r)polar((0:n)/n*2*pi,r+(0:n)*0)

```

Can be tested on octave-online.
@ptev already posted a MATLAB answer but mine uses far less bytes and isn't distorted.
We can save up another 6 bytes (or 4.5 including bonus) if we assume input can be given as variables `r`&`n` already existing in workspace - then just calling `polar((0:n)/n*2*pi,r+(0:n)*0)` is enough.

Also, example output (`n=5`,`r=3`):

---
Tags: code-golf, graphical-output, geometry, trigonometry
---