title: Tips for Golfing in Go

text:
# Question
Title: Tips for Golfing in Go
What general tips do you have for golfing in Go? I'm new to Code Golfing and looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Go.

Please keep to one tip per answer.

# Answer
Inspired by @EMBLEM's answer here.

You can put a package's functions in the global namespace when you import them like so:

```
package main

import ."fmt"

func main() {
    Printf("Hello World!")
}

```
> 19 votes

# Answer
You can name packages whatever you like when you import them.

```
package main

import f "fmt"

func main() {
    f.Printf("Hello World\n")
}

```

Learned this here.
> 12 votes

# Answer
Named return values can save a few bytes. For example:

```
func x()string{
r:="" //Do stuff
return r}

```

You can save 3 bytes with

```
func x()(r string){
//Do stuff
return}

```

It's more useful if you need to declare multiple variables at the start of your function.
> 12 votes

# Answer
If you need to compare many different values to a single one, it may be more space-efficient to use a `switch` with a single case.

```
if x==1||x==2||x==3||x==4{}
switch x{case 1,2,3,4:}

```
> 8 votes

# Answer
Go compiler has predefined `print` and `println` functions that don't require importing fmt, so instead of this.

```
package main
import."fmt"
func main(){Printf(`Hello World
`)}

```

You can write this.

```
package main
func main(){print(`Hello World
`)}

```

Note that this outputs to STDERR.
> 5 votes

# Answer
Go has different operator precedence for bit operations, `<<`, `>>`, `&`, etc. usually have lower precedence than `+` and `-` in most languages, but in Go they have the same precedence as `*` and `/`.

```
Precedence    Operator
5             *  /  %  <<  >>  &  &^
4             +  -  |  ^
3             ==  !=  <  <=  >  >=
2             &&
1             ||

```

This could be used to save some parentheses.

Most languages:

```
(a&b)*c

```

Go:

```
a&b*c

```
> 3 votes

# Answer
A lot of stuff in the for range loop is optional.

Standard version:

```
for i,v:=range a{
// Do stuff
}

```

If `i`, `v` has already been defined and can be overwritten:

```
for i,v=range a{
// Do stuff
}

```

If you don't care about value:

```
for i:=range a{
// Do stuff
}

```

If you don't care about value and `i` has already been defined:

```
for i=range a{
// Do stuff
}

```

If you don't care about index or value:

```
for range a{
// Do stuff
}

```

If you want an infinite loop:

```
for{
// Do stuff
}

```
> 3 votes

# Answer
Need a string to contain a newline? Don't write `\n`, create a raw string with backquotes and put a literal newline in it.

```
s:="\n" // 7 bytes
s:=`
` // 6 bytes

```
> 3 votes

# Answer
Declaring Multiple Variables:

```
i,s:=0,""

var(i int;s string)

```

Int From String Conversion: (limited but sometimes helpful)

```
n:=byte("9"[0])-48 // actual type is uint8

n,_:=strconv.Atoi("9")

```

And Vice Versa

```
s:=string(9+48)

s:=strconv.Itoa(9)

```
> 2 votes

# Answer
### When looping a constant `n` times, `for-range` is shorter up to `n <= 5`

If you need to loop a constant number of times, a `for range"..."{}` loop (where `...` is `n` characters) is shorter than a 3-part for loop up to `n <= 5` iterations.

The two loop forms are equivalent at `n == 5`:

```
for range`|||||`{}
for i:=0;i<5;i++{}

```

Past `n > 5`, use a 3-part loop.
> 2 votes

# Answer
You can put any number of opening braces on one line, but a line that contains opening braces may contain at most one closing brace.

Correct:

```
func main(){if true{switch{case 1==1:for{break
}}}}

```

Also correct:

```
func main(){if true{switch{case 1==1:for{break}
}}}

```

Also correct:

```
func main(){if true{switch{case 1==1:for{
break}}}}

```

Incorrect:

```
func main() {
    if true{for{break}}
}

```
> 1 votes

# Answer
Since an allowable output format is writing to reference arguments, it may save bytes to pass a pointer instead of returning a value.

```
func f(a,b string)string{if g(a)>g(b){return a};return b}
func f(a,b string, s*string){s=&b;if g(a)>g(b){s=&a}}

```
> 1 votes

# Answer
If you're using a C-style 3-part for-loop, if your loop variable isn't dependent on something outside of its scope for its initialization, declare it with your other variable declarations to save a byte.

In these examples, `i` is initialized independently of `a`

```
func f(){a:=3;for i:=0;i<a;i++{}}
// vs
func f(){a,i:=3,0;for;i<a;i++{}}

```
> 1 votes

# Answer
When taking a single character substring from a string and want to keep it as a string, use string slices to not get a rune:

```
string(s[0]) // 12 bytes
s[:1]        // 4 bytes

string(s[10]) // 13 bytes
s[10:11]      // 8 bytes

string(s[100]) // 14 bytes
s[100:101]     // 10 bytes

string(s[1000]) // 15 bytes
s[1000:1001]    // 12 bytes

string(s[10000]) // 16 bytes
s[10000:10001]   // 14 bytes

```

This method is shorter than `string(s[index])` up to getting from index `100000` and above, but indexing strings of that size are rare.
> 1 votes

# Answer
Don't declare variables in the `for`'s init statement:

```
for i:=0;i<n;i++{...}

```

By declaring it outside you may save a byte when you need a variable outside of it beacause you can now assign to it (`=`) instead of declaring it (`:=`):

```
i:=0
for;i<n;i++{...}
i=0
for;i<n;i++{...}

```

You might even save a byte if you're not using the `for`'s post-statement by removing the semicolons
> 1 votes

# Answer
Make full use of Go's first-class functions by assigning long library function names to one-letter variables.

```
import."strings"
r:=Replace

```
> 0 votes

# Answer
# Shuffle elements with `rand.Perm`

I discovered `math/rand.Perm` the other day, which returns a slice of integers from 0 to `n`, shuffled.

### For strings

Given an input string `k`, and you need to return a string, and we have that string as a named return, `Perm` is shorter because you don't need to real with the boilerplate for `Shuffle` or the swapping:

```
Shuffle(len(k),func(i,j int){k[i],k[j]=k[j],k[i]}) // 48 bytes
for i:=range k{j:=Intn(i);k[i],k[j]=k[j],k[i]}     // 44 bytes, -4, no separate string needed
for i:=range Perm(len(k)){e+=k[i:i+1]}             // 36 bytes, -12

```

### For slices

Assuming the same conditions as above but with a slice, it is still shorter:

```
Shuffle(len(k),func(i,j int){k[i],k[j]=k[j],k[i]}) // 48 bytes
for i:=range k{j:=Intn(i);k[i],k[j]=k[j],k[i]}     // 44 bytes, -4, no separate slice needed
for i:=range Perm(len(k)){e=append(e,k[i])}        // 41 bytes, -7

```
> 0 votes

# Answer
## Use `min` and `max` to clamp values (Go 1.21+)

Say you have 2 comparables `l` and `h`, where you must satisfy `l <= h`. It is 1 byte shorter to use the builtins than an if-statement.

```
// assuming
l,h := n, 0

if h<l{h=l}
h=max(h,l)

if l>h{l=h}
l=min(h,l)

// and the opposite
l,h := 0, n

if h>l{h=l}
h=min(h,l)

if l<h{l=h}
l=max(h,l)

```
> 0 votes

---
Tags: code-golf, tips
---


# Question
Title: Tell me how many math problems I have to do!
My teacher always gives me the most complicated set of math problems for homework. Like: `pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even`. And I want to know in advance how much time to set aside for my homework, but I don't want to have to figure all that out. That's why its your task to program it for me.

## Specifications

* You will get a string detailing the problems that I have to complete as args, stdio, etc.
* They will be comma separated (possibly `comma-space` separated)
* It will include single problems in the form of just a number (e.g. `79`)
* And ranges in the form `17-18` (again, you have to deal with optional spaces)
* The ranges are inclusive of both ends
* The ranges will optionally be suffixed by `odd` or `even`, which you have to take into account.
* A set of ranges/pages will be prepended by a page number in the form `pg. 545:` , again having to deal with optional spaces. You can safely ignore these, as you need to get the problems over all the pages
* The text may be in uppercase or lowercase, but will not be both.
* Return, stdout, etc. the number of problems I have to do for homework.
* Since this is , shortest code in bytes wins!

## Test Cases

```
pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even   ->    27
pg. 34: 1                                                    ->    1
PG. 565: 2-5,PG.345:7                                        ->    5
pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80                ->    70
pg.492: 2-4 odd,7-9 even                                     ->    2

```

# Answer
> 15 votes
# CJam, ~~61~~ ~~58~~ ~~51~~ ~~48~~ ~~46~~ ~~43~~ ~~41~~ 38 bytes

```
leuS-',/{':/W>:~_2*2<~z),>1f&\,5--~}%,

```

Verify the test cases in the CJam interpreter.

### How it works

```
leuS-      e# Read a line from STDIN, convert to uppercase and remove spaces.
',/        e# Split at commas.
{          e# For each chunk:
  ':/W>    e#   Split at colons and only keep the last chunk.
  :~       e#   Evaluate the string inside the array.
  _2*      e#   Copy the array, repeated twice.
  2<       e#   Keep only the first two elements.

           e#   In all possible cases, the array now contains exactly two
           e#   integers, which are equal in case of a single problem.

  ~        e#   Dump the array on the stack.
  z),      e#   Push [0 ... -N], where N is the second integer.
  >        e#   Discard the first M elements, where M is the first integer.
  1f&      e#   Replace each element by its parity.
  \,       e#   Push L, the length of the original array.

           e#   EVEN and ODD all push elements, so L is 1 for single problems,
           e#   2 for simple ranges, 5 for odd ranges and 6 for even ranges.

  5--      e#   Discard all elements equal to L - 5 from the array of parities.

           e#   This removes 0's for odd ranges, 1's for even ranges, -3's for
           e#   other ranges and -4's for single problems, thus counting only
           e#   problems of the desired parities.

  ~        e#   Dump the resulting array on the stack.
}%         e# Collect the results in an array.
,          e# Compute its length.

```

# Answer
> 10 votes
## Perl - 47 Bytes

```
#!perl -p054
{map$\+=($_%2x9^lc$')!~T,$&..$'*/\d+ ?-/}}{

```

Amended to pass the new test case.

---

**Original**

## Perl - 36 Bytes

```
#!perl -p054
$\+=/\d+ ?-/*($'-$&>>/o|e/i)+1}{

```

Counting the shebang as 4, input is taken from stdin.

---

**Sample Usage**

```
$ echo pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even | perl math-problems.pl
27

$ echo pg. 34: 1 | perl math-problems.pl
1

$ echo PG. 565: 2-5,PG.345:7 | perl math-problems.pl
5

$ echo pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80 | perl math-problems.pl
70

```

---

**Caveats**

For even/odd ranges, it is expected that at least one of the endpoints matches the parity of the range. For example, `11-19 odd`, `11-20 odd`, and `10-19 odd` will all be correctly counted as 5, but `10-20 odd` will be over-counted as 6.

# Answer
> 6 votes
# Python 2, ~~259~~ ~~253~~ ~~249~~ 239 bytes

**Try it here**

This can probably still be golfed more.

Edit: Fixed a bug that caused mine to not work for `2-4 even` as I had expected. Then made an adjustment for that fix. That fix saved me four bytes!

Edit: Now uses `input()` and **+2 bytes** for the two quotation marks the user must surround input with.

```
import re
c=0
for x in re.sub(r'..\..*?:','',input()).replace(' ','').split(','):
 y=x.split('-')
 if len(y)<2:c+=1
 else:
    a,b=y[0],y[1];d=int(re.sub('[A-z]','',b))-int(a)+1
    if b[-1]>':':d=d/2+d%2*(int(a)%2==ord(b[-3])%2)
    c+=d
print c

```

### Less golfed (with comments! :D):

I hope these comments help some. I'm still not quite sure if I explained that last complex line correctly or not.

```
import re
def f(s):
    c=0
    l=re.sub(r'..\..*?:','',s).replace(' ','').split(',')   # remove pg #'s and split
    for x in l:
        y=x.split('-')
        if len(y)<2:                                # if not a range of numbers
            c+=1
        else:
            a,b=y[0],y[1]                           # first and second numbers in range
            d=int(re.sub('[A-z]','',b))-int(a)+1    # number of pages
            if b[-1]>':':                           # if last character is not a digit
                # half the range
                # plus 1 if odd # of pages, but only if first and last numbers in the range
                #       are the same parity
                # ord(b[-3])%2 is 0 for even (v), 1 for odd (o)
                d=d/2+(d%2)*(int(a)%2==ord(b[-3])%2)
            c+=d
    print c

```

# Answer
> 4 votes
# Pyth, ~~43~~ ~~42~~ ~~44~~ 42 bytes

```
lsm-%R2}hKvMc-ecd\:G\-eK?}\ed}edGYc-rzZd\,

```

Try it online: Demonstration or Test harness

I think I can still chop one or two bytes.

### Explanation

```
lsm-%R2}hKvMc-ecd\:G\-eK?}\ed}edGYc-rzZd\,  implicit: z = input string
                                    rzZ     convert z to lower-case
                                   -   d    remove all spaces from z
                                  c     \,  and split by ","
  m                                         map each part d to:
               cd\:                           split d by ":"
              e                               and only use the last part (removes page number)
             -     G                          remove all letters (removes odd/even)
            c       \-                        split by "-"
          vM                                  and evaluate all (one or two) numbers
         K                                    and store the result in K
       }hK            eK                      create the list [K[0], K[0]+1, ..., K[-1]]
    %R2                                       apply modulo 2 to each element
   -                                          and remove:
                         }\ed                   "e" in d (1 for in, 0 for not in)
                        ?    }edG               if d[-1] in "abcde...z" else
                                 Y              dummy value
 s                                            combine all the lists
l                                             print the length

```

# Answer
> 3 votes
## Factor - 488 bytes:

```
USING: arrays ascii kernel math math.parser math.ranges pcre sequences ;
IN: examples.golf.homework

: c ( a -- b )
    >lower "(?:[,:]|^) *(\\d+) *(?:- *(\\d+) *(e|o)?)?" findall [
        rest [ second dup string>number swap or ] map
        dup length 1 = [ drop 1 ] [
            dup length 2 = [ first2 swap - 1 + ] [
                first3 "o" = [ [a,b] [ odd? ] count ] [
                    [a,b] [ even? ] count
                ] if
            ] if
        ] if
    ] map sum ;

```

# Answer
> 3 votes
# JavaScript (Spidermonkey console) - 139

It's just easier to test on the command line.

```
for(r=/[:,] *(\d+)[- ]*(\d+)? *(o|e)?/gi,m=readline(z=0);f=r.exec(m);z+=!b||((p=b-a)%2||!c|a%2^/e/i.test(c))+p/(2-!c)|0)[,a,b,c]=f
print(z)

```

Ungolfed:

```
// any number set after "pg:" or a comma
// \1 is FROM, \2 is TO, \3 is odd/even
r=/[:,] *(\d+)[- ]*(\d+)? *(o|e)?/gi;
m=readline();
z=0; // this is the sum.
while(f=r.exec(m)){
    [,from,to,oddEven]=f;
    if(!to) {
        z++;
    } else {
        if((to-from)%2) {
            // if to and from are not the same parity, add 1
            z++;
        } else {
            // if to and from are not the same parity...
            if(!oddEven) {
                // and we don't have a parity marker, add one
                z++;
            } else if(a%2 != /e/i.test(c)) {
                // if we do have a parity marker,
                // AND the parity of from and to matches the
                // parity of the oddEven sign, then add 1
                z++;
            }
        }
        // then add the difference between to-from and
        // if oddEven exists, divide by two and round down
        z+=(to-from)/(oddEven?2:1)|0;
    }

}
print(z);

```

# Answer
> 2 votes
# Bash 344 315 306 294 262 252 242 240

```
IFS=,
o(){ R=0;for ((i=$1;i<=$2;R+=i++%2));do :
done
}
e(){ q=$R;o $*;((R=q-R))
}
for c in ${1,,};do
c=${c#*:}
m=${c##* }
l=${c%-*}
l=${l// }
h=${c#*-}
[[ a< $m ]]&&h=${h% *}
h=${h// }
((R=h-l+1))
eval "${m::1} $l $h"
((t+=R))
done;echo $t

```

I don't think I've golfed this as much as is possible but not bad for a first submission. Commented version below.

```
IFS=, # Setup IFS for the for loops, We want to be able to split on commas

o(){ # Odd
    R=0  # Reset the R variable

    # Increments R for each odd element in the range
    # $1-$2 inclusive
    for ((i=$1;i<=$2;R+=i++%2));do
        : # Noop command
    done
}

e(){ # Even
    # Save R, it contains the total number of elements between low
    # and high
    q=$R
    # Call Odd, This will set R
    o $*
    # Set R = total number of elements in sequence - number of odd elements.
    ((R=q-R))
}

# This lowercases the firs arg. IFS causes it to split on commas.
for c in ${1,,};do
    c=${c#*:}  # Strips the page prefix if it exists
    m=${c##* }  # Capture the odd/even suffix if it exists
    l=${c%-*}  # Capture low end of a range, Strips hyphen and anything after it
    l=${l// }  # Strips spaces
    h=${c#*-}  # Capture high end of a range, Strips up to and including hyphen

    # If we have captured odd/even in m this will trigger and strip
    # it from the high range variable.
    [[ a< $m ]]&&h=${h% *}
    h=${h// }  # Strip Spaces

    # Give R a value.
    # If we are in a range it will be the number of elements in that range.
    # If we arent l and h will be equal are R will be 1
    ((R=h-l+1))

    # Call the odd or even functions if we captured one of them in m.
    # If we didnt m will contain a number and this will cause a warning
    # to stderr but it still works.
    eval "${m::1} $l $h"

    # Add R to total
    ((t+=R))
done

# Print result
echo $t

```

Run the test cases:

```
bash math.sh "pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even"
bash math.sh "pg. 34: 1"
bash math.sh "PG. 565: 2-5,PG.345:7"
bash math.sh "pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80"
bash math.sh "pg.492: 2-4 odd,7-9 even"

```

Depending on how I read the rules it could be possible to save another 4 bytes. If even/odd is always lowercase `${1,,}` can be changed to `$1`

# Answer
> 1 votes
# JavaScript (*ES6*), 149

Run snippet in Firefox to test

```
F=s=>s.replace(/([-,.:]) *(\d+) *(o?)(e?)/ig,(_,c,v,o,e)=>
  c=='-'?(t+=1+(o?(v-(r|1))>>1:e?(v-(-~r&~1))>>1:v-r),r=0)
  :c!='.'&&(t+=!!r,r=v)
,r=t=0)&&t+!!r

// Less golfed

U=s=>{
  var r = 0, // value, maybe range start
  t = 0; // total
  s.replace(/([-,.:]) *(\d+) *(o?)(e?)/ig, // execute function for each match
    (_ // full match, not used
     , c // separator char, match -:,.
     , v // numeric value
     , o // match first letter of ODD if present
     , e // match first letter of EVEN if present
    )=>
    {
      if (c == '-') // range end
      {
        t++; // in general, count range values as end - start + 1
        if (o) // found 'odd'
        {
          r = r | 1; // if range start is even, increment to next odd
          t += (v-r)>>1; // end - start / 2
        }
        else if (e) // found 'even'
        {
          r = (r+1) & ~1; // if range start is odd, increment to next even
          t += (v-r)>>1; // end - start / 2
        }
        else
        {
          t += v-r; // end - start
        }
        r = 0; // range start value was used
      }
      else if (c != '.') // ignore page numbers starting with '.'
      {
        // if a range start was already saved, then it was a single value, count it
        if (r != 0) ++t;
        r = v; // save value as it counld be a range start
      }
    }
  )
  if (r != 0) ++t; // unused, pending range start, was a single value
  return t
}

// TEST

out=x=>O.innerHTML+=x+'\n';

test=["pg. 546: 17-19, 22, 26, pg. 548: 35-67 odd, 79, 80-86 even",
"pg. 34: 1", "PG. 565: 2-5,PG.345:7",
"pg. 343: 5,8,13 - 56 even,pg. 345: 34 - 78,80"];

test.forEach(t=>out(t + ' --> ' + F(t)))
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
# C++ ~~226~~ ~~224~~ 222

I know I'm kinda late for the party, but this seemed like a fun problem and lack of entries using C-family languages bothered me.

So here's a C++ function using no regexp or string substitution, just some simple math:

```
void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

```

**Ungolfed**:

```
void f()
{
  char c;
  int o=0,i,j;
  while(cin>>c)
    c=='p'||c==80?cin.ignore(9,58):cin.unget(),
    cin>>i>>c&&c==45?
      cin>>j>>c&&(c=='e'||c=='o')?
        cin.ignore(9,44),
        c=='e'?
          i+=i&1,j+=!(j&1)
        :(i+=!(i&1),j+=j&1),
        o+=(j-i)/2
      :o+=j-i
    :0,
    ++o;
  cout<<o;
}

```

I didn't say it would be readable, now did I? :) Ternary operators are hell. I tried my best to (sort of) format it, though, so I hope it helps at least a little bit.

**Usage**:

```
#include <iostream>
using namespace std;

void f(){char c;int o=0,i,j;while(cin>>c)c=='p'||c==80?cin.ignore(9,58):cin.unget(),cin>>i>>c&&c==45?cin>>j>>c&&(c=='e'||c=='o')?cin.ignore(9,44),c=='e'?i+=i&1,j+=!(j&1):(i+=!(i&1),j+=j&1),o+=(j-i)/2:o+=j-i:0,++o;cout<<o;}

int main()
{
  f();
}

```

# Answer
> 0 votes
## **Python 2 - 163 bytes:**

Try it here

Input must be given inside quotes

```
import re
print len(eval(re.sub('([^,]+:|) *(\d+) *-? *(\d*)(?=.(.)).*?,',r'[x for x in range(\2,\3+1 if \3.0 else \2+1)if x%2!="oe".find("\4")]+',input()+',[]')))

```

**Explanation:**

The general approach is to convert the existing input into valid python, then evaluate this. Each comma separated value is converted to an array, which are then all appended together and the length gives the final result.

For example, with the input `12-15 odd,19`, before evaluation the regex substitution will produce:

```
[x for x in range(12,15+1 if 15.0 else 12+1)if x%2!="oe".find("o")]
+[x for x in range(19,+1 if .0 else 19+1)if x%2!="oe".find("[")]
+[]

```

To break this down further:

* `15+1 if 15.0 else 12+1` This bit will make sure the second argument of range() is correct depending if there is a range or a single value given (if \3 is empty, \3.0 will evaluate to false).
* `if x%2!="oe".find("o")` Depending on the value found two characters away from the final digit in the range (`(?=.(.))` in the regex - lookahead two characters without consuming them), there are three possible outcomes:

+ `x%2!="oe".find("o")` evaluates to `x % 2 != 0` (only odd matched)
    + `x%2!="oe".find("e")` evaluates to `x % 2 != 1` (only even matched)
    + `x%2!="oe".find("[")` evaluates to `x % 2 != -1` (this character could be multiple things as it's just two characters away from the last digit, but will only be o or e if odd/even is intended)
* The seemingly random +\[\] on the end is to ensure that the last token in the comma-separated list has a character two away from the last digit, but also allows us to append something to the end to use up the last '+' which would have been trailing otherwise.

# Answer
> 0 votes
# Go, 358 bytes

```
import(."fmt";."regexp";."strings")
func f(s string)(O int){C:=Contains
for _,m:=range MustCompile(`pg\.\d+:`).Split(ReplaceAll(ToLower(s)," ",""),-1){for _,r:=range Split(m,",") {if r==""{continue}
l,h,e,o:=0,0,C(r,"even"),C(r,"odd")
Sscanf(r,`%d-%d`,&l,&h)
h=max(h,l)
h++
for i:=l;i<h;i++{if e&&i%2<1{O++}else if o&&i%2>0{O++}else if !e&&!o{O++}}}}
return}

```

Attempt This Online!

Does some input preprocessing (to lowercase, remove spaces), then splits on the pages. After that, for each problem range (matches split on commas), add to the problem count. If it's even only count on even indexes, and the same for odds. If neither, count on each index.

---
Tags: code-golf, natural-language
---


title: Tips for golfing in Perl?

text:
# Question
Title: Tips for golfing in Perl?
What general tips do you have for golfing in Perl? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Perl (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
## TMTOWTDI

That's the most important Perl golfing tip you need to know. Whenever you're looking at some too-long sequence of characters you absolutely have to have in order to accomplish your task, ask yourself if there isn't some other way to get the same effect using a different feature. There usually is. Here are just a handful:

* `~~` enforces a scalar context and is 4 chars shorter than `scalar`.
* `y///c` is one char shorter than `length` when getting the length of `$_`.
* Need to iterate over the chars in `$_`? Replace `split//` with `/./gs`. (Or use `/./g` if you also want to skip newlines.) This works with other variables: replace `split//,$x` with `$x=~/./gs`.
* Every Perl builtin returns something. `print` returns 1, for example, to indicate successful I/O. If you need to initialize `$_` to a true value, for example, `$_=print$foo` allows you to kill two birds with one stone.
* Almost every statement in Perl can be written as an expression, allowing it to be to used in a wider variety of contexts. Multiple statements can be become multiple expressions chained together with commas. Tests can be done with short-circuiting operators `?:` `&&` `||`, and also with `and` and `or`, which do the same thing but with precedence lower than all other operators (including assignment). Loops can be done via `map` or `grep`. Even keywords like `next`, `last` and `return` can be used in an expression context, even though they don't return! Keeping these kinds of transformations in mind give you opportunities to replace code blocks with expressions that can be stuffed into a wider variety of contexts.
> 32 votes

# Answer
Abuse Perl's special variables!

* As noted in a previous answer `$/` and `$"` are initialized by default to `"\n"` and `" "`, respectively.
* `$,` and `$\` are both set to `undef` by default, and are 3 chars shorter.
* Setting `$\` to a value will cause it to be appended to every `print`. For example: `perl -ple '$\="=".hex.$/'` is a handy hex-to-decimal converter.
* If you're not reading files from the command-line, you can use the `-i` command-line switch as an extra channel for inputting a string. Its value will be stored in `$^I`.
* `$=` forces whatever is assigned to it to be an integer. Try running `perl -ple '$_=$==$_'` and giving it various inupts. Likewise, `$-` forces its value to be a non-negative integer (i.e. a leading dash is treated as a non-numeric character).
* You can use `$.` as a boolean flag that is automatically reset to a true (nonzero) value on every iteration of a `while(<>)` loop.
> 26 votes

# Answer
# `-n` and unmatched curly brackets

It is well known that the command line switch `-n` can be used to execute the script once for every line.

`perl --help` says:

```
  -n                assume "while (<>) { ... }" loop around program

```

What it doesn't say explicitly is that Perl doesn't just assume a loop around the program; it *literally* wraps `while (<>) { ... }` around it.

This way, the following commands are equivalent to each other:

```
 perl -e 'while(<>){code}morecode'
 perl -ne 'code;END{morecode}'
 perl -ne 'code}{morecode'

```

# `-p` and unmatched curly brackets

Similarly to the above, the `-p` switch wraps `while (<>) { ... ; print }` around the program.

By using unmatched curly brackets, `perl -p 'code}{morecode'` will only print once after executing `code` for all lines of input, followed by `morecode`.

Since `$_` is undefined when `morecode;print` is executed, the output record separator `$\` can be abused to print the actual output.

For example

```
perl -pe '$\+=$_}{'

```

reads one number per line from STDIN and prints their sum.
> 23 votes

# Answer
Use `$_` to eliminate scalar references. It is the special variable that is used as a default by most functions, and just leaving out parameters is a shortcut to reference this variable.

By changing `$n` to `$_`, you can change `$n=<>;chop$n;print$n` to `$_=<>;chop;print`

Here, the `print` function prints the contents of `$_` by default, and `chop` also works on `$_`.
> 18 votes

# Answer
Use Perl's special variables where-ever you can, eg:

* Use `$"` instead of `" "`
* Use `$/` instead of `"\n"`

They have the added benefit of being a guaranteed one-character long identifier, with help from the lexer. This makes it possible to glue it to the keyword following it, as in: `print$.for@_`

The list of all the special variables is available here: Special Variables
> 17 votes

# Answer
Don't use `qw`. This is waste of two characters that could be used in better way. For example, don't write the following.

```
@i=qw(unique value);

```

Instead use barewords.

```
@i=(unique,value);

```

Or if you cannot use barewords, use `glob` syntax.

```
@i=<unique value>;

```

`glob` syntax can also be used for interesting effects.

```
@i=<item{1,2,3}>;

```
> 16 votes

# Answer
Use statement modifiers instead of compound statements.

Compound statements tend to require parentheses for the argument and braces for the block, whereas statement modifiers need neither.

Compare:

* `$a++,$b++while$n--` vs `while($n--){$a++;$b++}`
* `chop$,if$c` vs `if($c){chop$,}`

Note that the last example ties with `$c&&chop$,`, but starts really shining for most multi-statement operations. Basically anything that loses operator precedence to `&&`.
> 13 votes

# Answer
I'm sure some of these have formal names and I'm just not aware of them.

* If you have a while loop (or a for loop you can make into a while loop) you can define the "while" after the command: `print $n++ while ($n < 10)`
* If you need to read everything from STDIN into a string: `$var = join('',<>)`
* As CeilingSpy pointed out, using $/ instead of \n is faster in some situations: `print ('X'*10) . "\n";` is longer than `print ('X'*10) . $/;`
* Perl's `say` function is shorter than `print`, but you'll have to run the code with `-E` instead of `-e`
* Use ranges like `a..z` or even `aa..zz`. If needed as a string, use `join`.
* Incrementing strings: `$z = 'z'; print ++$z;` will display `aa`

That's all I can think of right now. I may add some more later.
> 11 votes

# Answer
Don't `use strict`. (don't quote me on this, PCG.SE context kinda matters) And, more importantly, don't code as if under strict. The usual suspects:

* don't `my`-declare variables if you can avoid it. The only variables that really need `my` are those you want lexically scoped. That's barely any of them when golfing, where you don't need scope protection and tend to fully control recursion.
* don't quote one-word strings: (example). Do ensure you don't have a function with the same name, though.
> 11 votes

# Answer
# Use non-word characters as variable names

Using `$%` instead of `$a` can allow you to place the variable name right next to an `if`, `for` or `while` construct as in:

`@r=(1,2,3,4,5);$%=4;` `print$_*$%for@r`

Many can be used, but check the docs and @BreadBox's answer for which ones have magic effects!

---

# Use map when you can't use statement modifiers

If you can't use statement modfiers as per @JB's answer, map might save a byte:

`for(@c){}` vs. `map{}@c;`

and is useful if you want to do nested iterations as you can put postfix `for` loops inside the `map`.

---

# Use all the magic Regular Expression variables

Perl has magic variables for 'text before match' and 'text after match' so it is possible to split to groups of two with potentially fewer characters:

```
($x,$y)=split/,/,$_;
($x,$y)=/(.+),(.+)/;
/,/; # $x=$`, $y=$'
# Note: you will need to save the variables if you'll be using more regex matches!

```

This might also work well as a replacement for `substr`:

```
$s=substr$_,1;
/./;# $s=$'

$s=substr$_,4;
/.{4}/;# $s=$'

```

If you need the contents of the match, `$&` can be used, eg:

```
# assume input like '10 PRINT "Hello, World!"'
($n,$c,$x)=split/ /,$_;
/ .+ /; # $n=$`, $c=$&, $x=$'

```

---

# Replace subs with long names with a shorter name

If you call say `print` four or more times in your code (this obviously varies with the length of the routine you're calling), replace it with a shorter sub name:

```
sub p{print@_}p;p;p;p

```

vs.

```
print;print;print;print

```

---

# Replace conditional incrementors/decrementors

If you have code like:

```
$i--if$i>0

```

you can use:

```
$i-=$i>0

```

instead to save some bytes.

---

# Convert to integer

If you aren't assigning to a variable and so can't use breadbox's tip, you can use the expression `0|`:

```
rand 25 # random float eg. 19.3560355885212

int rand 25 # random int

0|rand 25 # random int

rand 25|0 # random int

~~rand 25 # random int

```

It's worth noting however than you don't need to use an integer to access an array index:

```
@letters = A..Z;
$letters[rand 26]; # random letter

```
> 11 votes

# Answer
`redo` adds loop behavior to a block without `for` or `while`. `{redo}` is an infinite loop.
> 10 votes

# Answer
Don't parenthesize function calls.

Perl lets you call a known (core or predeclared) function using the `NAME LIST` syntax. This lets you drop the `&` sigil (if you were still using it) as well as the parentheses.

For example: `$v=join'',<>`

Full documentation
> 7 votes

# Answer
You can run multiple different statements within nested ternary logic.

Suppose you have a big `if`-`elsif` statement. This could be any logic and any number of statements.

```
if( $_ < 1 ) {
    $a=1;
    $b=2;
    $c=3;
    say $a.$b.$c;
} elsif($_ < 2 ) {
    $a=3;
    $b=2;
    $c=1;
    say $a.$b.$c;
} elsif( $_ < 3) {
    $a=2;
    $b=2;
    $c=2;
    say $a.$b.$c;
}

```

You can use `(cmd1, cmd2, cmd3)` inside the ternary operator to run all of the commands.

```
$_ < 1 ?
    ($a=1,$b=2,$c=3,say$a.$b.$c):
$_ < 2 ?
    ($a=3,$b=2,$c=1,say$a.$b.$c):
$_ < 3 ?
    ($a=2,$b=2,$c=2,say$a.$b.$c):
0; #put the else here if we have one

```

Here's a dummy example:

```
perl -nE'$_<1?($a=1,$b=2,$c=3,say$a.$b.$c):$_<2?($a=3,$b=2,$c=1,say$a.$b.$c):$_<3?($a=2,$b=2,$c=2,say$a.$b.$c):0;' <(echo 2)

```
> 6 votes

# Answer
# If you need an alternating boolean

Instead of doing something like `$-++%2`, use `$|--`.

Try it online!
> 6 votes

# Answer
Try to use the value of an assignment expression, like so:

```
# 14 characters
$n=pop;$o=$n&1

# 13 characters, saves 1
$o=($n=pop)&1

```

This works because `$n` is 2 characters in Perl. You may change `$n` to `()` at no cost, and save 1 semicolon by moving the assignment into the parentheses.
> 5 votes

# Answer
# Use the free `;` from `-n`/`-p`

Thanks to @Neil for letting me know this tip wasn't in the list!

Further to @Dennis' tip of using the implicit code added via `-n`/`-p`, a `;` is inserted as well and using this to your advantage, you can sometimes save a byte:

Using `$;` as the final variable:

`$a=$_*say$--1?"...":$_-1if$-=$_-1-$a` vs. `$;=$_*say$--1?"...":$_-1if$-=$_-1-$`

Used with a quote-like operator:

`s/(.)(.)/$2$1/` vs. `s;(.)(.);$2$1`

Or used with a list:

`pop@a;push@a,/\w+/g;$,="/";/{/&&say@a` vs. `pop@;;push@;,/\w+/g;$,="/";/{/&&say@`

The only stipulation is that it needs to be the last statement.
> 5 votes

# Answer
# Use `select(undef,undef,undef,$timeout)` instead of `Time::HiRes`

(Taken from https://stackoverflow.com/a/896928/4739548)

Many challenges require you to sleep with greater precision than integers. `select()`'s timeout argument can do just that.

```
select($u,$u,$u,0.1)

```

is much more efficient than:

```
import Time::HiRes qw(sleep);sleep(0.1)

```

The former is only 20 bytes, whereas the latter takes up 39. However, the former requires you aren't using `$u` and have never defined it.

If you're going to use it a lot importing `Time::HiRes` pays off, but if you only need it once, using `select($u,$u,$u,0.1)` saves 19 bytes, which is definitely an improvement in most cases.
> 4 votes

# Answer
## Use expression regexes.

Decent illustration of this is the following code shaping the input into sine wave:

```
s/./print" "x(sin($i+=.5)*5+5).$&/eg;

```

As you can see, it's a pretty compact way of iterating over characters in standard input. You could use other regex to change the way how things are matched.
> 3 votes

# Answer
# Use globs like string literals

Occasionally (often when dealing with or challenges) you benefit greatly from the ability to nest string literals. Normally, you'd do this with `q(…)`. However, depending on what characters you need inside the string, you may be able to save a byte and use `<…>`, the glob operator. (Note that what's inside the angle brackets can't look like a filehandle, and can't look like it's meant to be expanded into a list of filenames, which means that quite a lot of characters won't work correctly.)
> 2 votes

# Answer
# Useful escape sequences

See perlrebackslash, but you can potentially save a lot of bytes using these effectively.

In matches:

```
[A-Za-z]        \pl
[^A-Za-z]       \Pl
(?<=\w)         \B

```

In replacements (or double quoted strings):

```
\utext          Text            (e.g s/ (.)/uc$1/e vs. s/ (.)/\u$1/)
\Utext          TEXT
\lTEXT          tEXT
\LTEXT          text

```
> 2 votes

# Answer
# Don't reassign `$_` in nested `for`/`map`s

If you aren't using `m//` or `s///` in the body of the loop, you can make the most of `$'` in a nested loop by performing an empty match (`//`) and using `$'` instead of assigning `$_` to another variable:

```
$i=$_,say map{qw(0 * +)[max(abs,abs$i)%3]}@;for @;=- --$_..$_

```

vs.

```
//,say map{qw(0 * +)[max(abs,abs$')%3]}@;for@;=- --$_..$_

```
> 2 votes

# Answer
# Use `sub` signatures

If you're submitting a function, using `-Mfeature+signatures` might save you 4 bytes vs. using `@_`:

```
sub{($a,$b)=@_;...}

sub($a,$b){...}

```
> 2 votes

# Answer
# Use hash keys for random ordering.

If a set of items needs to be in a random order, or you need a (pseudo)random subset of items, storing them as hash keys will allow them to be ordered randomly without a call to `rand`. The order will remain consistent within a program run as long as no insertions or deletions are made to the hash.

# Hash keys can be defined quickly

If the information to be stored/randomized is already in an array, the hash can quickly be created with:

```
 @hash{@array}++;

```

The values of the hash are not particularly useful here, but then the array elements can be retrieved in a random order with:

```
@random_ordered_array = keys %hash;

```
> 2 votes

# Answer
# Shorten your print statements

Unless the challenge specifies otherwise, you don't need trailing newlines.
Our 'challenge' says 'output a random number from 0 to 9 to STDOUT'. We can take this code (28 bytes):

```
$s=int(rand(10));print"$s\n"

```

And shorten it to this (25 bytes):

```
$s=int(rand(10));print $s

```

by simply printing the variable. This last one only applies to this challenge specifically (19 bytes):

```
print int(rand(10))

```

but that only works when you don't have to do anything to the variable in between assignment and printing.
> 1 votes

# Answer
# If you need a variable that is falsy on first call and truthy thereafter

Instead of something like `!!$x++`, use `$|++`.

Try it online!
> 1 votes

# Answer
# Use `s///` to set `$_` instead of `$_="..."`

If you ever need to set an empty `$_` to, or add a prefix of, a value that would otherwise require quoting, using `s//<value to set>/` can save a byte:

```
$_="A'B"; # vs:
s//A'B/;

```
> 1 votes

# Answer
Chain transliterations and substitutions with the `/r` modifier instead of assigning to `$_` first, and directly use the result, rather than using `$_` (possibly implicitly) in a separate statement. For example, if your code does:

```
$_="complex_string";s/pat/repl/;print

# Or when $_ is in use, the even more verbose
$a="complex_string";$a=~/pat/repl/;print$a

```

you can shave two characters, and free up `$_` for other uses, with:

```
print"complex_string"=~s/pat/repl/r

```
> 0 votes

# Answer
# Arrays become strings become numbers

When needing to do math involving the first element of an array, `"@array"` will evaluate to the same value as `$array[0]` and is one byte shorter. This assumes that the value of `$"` has not been modified in a way that would join the elements of the array into a single number when concatenated together.

This is because `"@array"` expands to `$array[0].$".$array[1].$".$array[2]...`. When Perl parses a scalar in a numeric context, it stops parsing it after encountering a character that is not part of the number, leaving just the first number in the string to be used as the value.
> 0 votes

# Answer
# Two copies of input

The `-F` and `-a` give you a split version of your input in `@F` as well as the complete input in `$_`. Both `@F` and `$_` can be used and modified as needed.
> 0 votes

---
Tags: code-golf, tips, perl
---


title: Is this a powerful number?

text:
# Question
Title: Is this a powerful number?
A **powerful number** is a positive integer \\$n\\$ such that for every prime \\$p\\$ that divides \\$n\\$, \\$p^2\\$ also divides \\$n\\$. Or equivalently, \\$n\\$ is powerful if and only if it can be written in the form \\$n = a^2b^3\\$, where \\$a\\$ and \\$b\\$ are positive integers.

For example, \\$972 = 2^2 \times 3^5\\$ is powerful, because \\$2^2\\$ and \\$3^2\\$ both divide \\$972\\$. And we have \\$972 = 6^2 \times 3^3\\$.

\\$961 = 31^2\\$ is also powerful, because \\$31^2\\$ divides \\$961\\$. And we have \\$961 = 31^2 \times 1^3\\$.

On the other hand, \\$1001 = 7 \times 11 \times 13\\$ is not powerful, because \\$7^2\\$ does not divide \\$1001\\$. It is not possible to write \\$1001\\$ in the form \\$a^2b^3\\$.

Here is a list of all the powerful numbers less than 1000:

```
1, 4, 8, 9, 16, 25, 27, 32, 36, 49, 64, 72, 81, 100, 108, 121, 125, 128, 144, 169, 196, 200, 216, 225, 243, 256, 288, 289, 324, 343, 361, 392, 400, 432, 441, 484, 500, 512, 529, 576, 625, 648, 675, 676, 729, 784, 800, 841, 864, 900, 961, 968, 972

```

This is sequence A001694 in the OEIS.

## Task

Given a positive integer \\$n\\$, determine whether or not it is a powerful number.

This is , so the shortest code in bytes wins.

This is also a so you may use your language's convention for truthy/falsy (swapping truthy and falsy is allowed), or use two distinct, fixed values to represent true or false.

# Answer
> 9 votes
# Python 3, 43 bytes

Returns `False` for a powerful number, and `True` otherwise.

```
f=lambda n,i=1:i>n or(n/i)**.5%i>0<f(n,i+1)

```

Try it online!

Checks the condition that `n` is in the form `a^2*b^3` by asserting that `n/a^3` is a perfect square. In Python this would look something like `(n/a**3)**.5%1==0`. This condition can be rearranged so that it is slightly golfier:

```
(n/a**3)**.5%1==0
n**.5/a**1.5%1==0
n**.5/a**.5/a%1==0
(n/a)**.5/a%1==0
(n/a)**.5%a==0

```

# Answer
> 7 votes
# Jelly, 4 bytes

```
ÆE1e

```

Try it online!

Inverted native truthy/falsy semantics: 0 for powerful numbers, 1 otherwise.

```
  1e    Is 1 an element of
ÆE      the array of the input's prime exponents?

```

# Answer
> 6 votes
# , 24 bytes

```
\(n)all((n/1:n)^.5%%1:n)

```

Attempt This Online!

Port of @dingledooper's approach.

---

### , 26 bytes

```
\(n,i=1:n)n%in%(i^2%o%i^3)

```

Attempt This Online!

Uses the alternative characterization from the question.

# Answer
> 6 votes
# Python, 43 bytes

```
f=lambda n,c=1:f(n,c+1)if c**n%n else n/c%c

```

Try it online!

Outputs Truthy/Falsey reversed. A different method than dingledooper's solution, without using square roots.

The idea is to find the square-free part `c` of `n`, that is, the product of the distinct prime factors of `n`. We do this by counting up to the smallest `c` where `c**n%n` is 0, which checks that the prime factors of `c`, if copied many times, cover those of `n`.

Having found `c`, we check whether `n/c%c` is zero, which is equivalent to `n` being divisible by `c**2`. This confirms that `n` includes each of its prime factors at least twice. This also works in Python 2 where `/` is integer division rather than float division, since `n` is divisible by `c`, for a solution with only exact integer arithmetic.

Rather than finding the smallest `c` with `c**n%n`, we could instead check all values of `c` from `1` to `n` for one where `c**n%n` and `n/c%c` are both 0. This could look like:

**44 bytes**

```
f=lambda n,c=1:c>n or(c**n%n+n/c%c)*f(n,c+1)

```

Try it online!

**39 bytes with exit code**

```
def f(n,c=1):c**n%n+n/c%c>0!=f(n,-~c%n)

```

Try it online!

From *@loopy walt*

## Python 2, 42 bytes

```
d=n=input()
while n%d**2:d-=1
print d**n%n

```

Try it online!

Finds the largest value `d` where `n` is divisible by `d**2`, then checks that it includes each distinct prime factor of `n` via `d**n%n` being zero.

# Answer
> 5 votes
# TI-BASIC (TI-84 Plus/Plus CE), ~~35~~ 27 Bytes

-8 bytes thanks to Bbrk24

```
Prompt A:For(B,1,A:If not(fPart(√(A/B:Stop:End:Disp 0

```

The thing right after `A/B` is a cube (3). The thing right before the `A/B` is a sqrt symbol.

Does nothing and terminates if your number is powerful and prints `0` and terminates if your number is not powerful.

**Ungolfed**

```
Prompt A
For(B,1,A
If not(fPart(√(A/B
Stop
End
Disp 0

```

**Explained**

```
Prompt A              Asks user for input A
For(B,1,A             For loop: increase B by 1 from 1 until it reaches A
If                    If...
            √(        square root of...
              A/B    A/B^3...
  not(fPart(          is a whole number...
Stop                  then stop execution.
End                   End of while loop, go back to While A>B
Disp 0                If, eventually, B does exceed A, then A is not a powerful number.

```

TI-BASIC programs are scored by tokens bytes, not characters.
TI-BASIC also completes parentheses for you.

### Edit: Test cases

**Truthy**:

**Falsy**:

# Answer
> 4 votes
# , ~~12 10~~ 8 bytes

```
1 e._&q:

```

Try it online!

*-2 by using Unrelated String's approach of checking for 1 instead of verifying that every exponents was 2 or more*

*-2 thanks to Bubbler for a shorter way to get prime exponents*

* `_&q:` shows the number's prime exponents
* `1 e.` checks if all exponents are greater than 1, by checking if 1 is an element and using 0 for truthy and 1 for falsy

# Answer
> 4 votes
# Excel, 42 bytes

```
=LET(a,SEQUENCE(A1),OR(a^2*TOROW(a^3)=A1))

```

Input in cell `A1`.

# Answer
> 4 votes
# K (ngn/k), 18 bytes

```
{|/~1!%x%/3#,1+!x}

```

Try it online!

Works more like dingledooper's Python solution.

```
{|/~1!%x%/3#,1+!x}
             1+!x   1..x
       x%/3#,       starting from x, divide by above three times
      %             square root of each
 |/~1!              test if any of them has zero fractional part

```

---

# K (ngn/k), 22 bytes

```
{|//x=*/:/1_*\3#,1+!x}

```

Try it online!

A bit of a convoluted way to check if the given number `x` is `a^2 * b^3`. Returns 1 if `x` is a powerful number, 0 otherwise.

```
{|//x=*/:/1_*\3#,1+!x}
                 1+!x   1..x inclusive -> A
              3#,       an array that contains three copies of A
            *\     cumulative product (A; A^2; A^3)
          1_       drop first
      */:/    reduce by cartesian product by multiplication
    x=        boolean matrix indicating each number is equal to input
 |//          max of all booleans

```

# Answer
> 4 votes
# Dyalog APL, 21 bytes

```
⊢(⊣|*⍨)0⌈/∘⍸⍤=⊢|⍨2*⍨⍳

```

port of xnor's Python answer. Outputs inverse truthy value

```
⊢(⊣|*⍨)0⌈/∘⍸⍤=⊢|⍨2*⍨⍳ ⍝ implicit n
                    ⍳ ⍝ list values 1..n
                 2*⍨ ⍝ square each value
              ⊢|⍨    ⍝ mod by n
        0   =        ⍝ find where index is 0
         ⌈/∘⍸⍤        ⍝ Get max index divisible (d)
⊢(⊣|*⍨)              ⍝ then check d^n mod n

```

# Answer
> 4 votes
# C, ~~69~~ 63 bytes

-6 bytes thanks to @c-- suggesting to reverse the loops and pointing out that I'd managed to leave in an unused variable.

```
i,j;f(n){for(i=n;i;i--)for(j=n;j;j--)n*=i*i*j*j*j!=n;return!n;}

```

Try it online!

# Answer
> 3 votes
# Factor \+ `math.primes.factors math.unicode`, ~~30~~ 29 bytes

```
[ group-factors unzip 1 ∋ ]

```

Try it online!

Port of Unrelated String's Jelly answer.

-1 by using `unzip` instead of `values` to get at the exponents

* `group-factors` get an associative array of a number's prime factors and exponents
* `unzip` get just the exponents
* `1 ∋` is 1 in this?

# Answer
> 3 votes
# Octave, 22 bytes

```
@(n)n-(t=1:n).^2'*t.^3

```
* The output for powerful input is a matrix containing at least one entry equal to 0, which is falsy in Octave.
* The output for a non-powerful input is a non-empty matrix with all entries different than zero, which is truthy.

Try it online! The footer code contains truthiness/falsihood test.

Or verify all test cases. The footer code displays the input number if powerful (falsy output), or `--` otherwise (truthy output).

# Answer
> 3 votes
# Vyxal, 4 bytes

```
ǏΠ²Ḋ

```

Try it Online!

Uses Command Master's insight that these are numbers where the product of the distinct prime factors of the input is divisible by the input.

```
ǏΠ²Ḋ  # implicit input of integer
Ǐ     # distinct prime factors
 Π    # the product of this list
  ²   # squared
   Ḋ  # is divisible by the (implicit) input

```

# Answer
> 3 votes
# Nekomata \+ `-e`, 3 bytes

```
ƒ1>

```

Attempt This Online!

```
ƒ1>
ƒ       Factor
 1>     Check if all exponents are greater than 1

```

# Answer
> 2 votes
# 05AB1E, 3 bytes

```
Ó1å

```

Outputs an inverted 05AB1E boolean: \\$1\\$ if it's NOT a powerful numbers; \\$0\\$ if it is a powerful number (only `1` is truthy in 05AB1E).

Port of *@UnrelatedString*'s Jelly answer, so make sure to upvote that answer as well!

Try it online or verify all test cases.

**Explanation:**

```
Ó    # Get a list of exponents of the (implicit) input's prime factorization
 1å  # Does this list contain a 1?
     # (after which the result is output implicitly)

```

# Answer
> 2 votes
# Arturo,  ~~33~~  30 bytes

```
$=>[in? 1tally factors.prime&]

```

Try it!

Port of Unrelated String's Jelly answer.

```
$=>[               ; a function where input is assigned to &
    in? 1          ; is 1 in
    tally          ; counts of
    factors.prime& ; input's prime factors
]                  ; end function

```

# Answer
> 2 votes
# Racket, 101 bytes

```
(define(f n)((λ(D ?)(=(count(λ(p)(and(? p n)(?(sqr p)n)))D)(length D)))(prime-divisors n)divides?))

```

Try it online!

---

## Explanation

We create a function `f` that takes one input `n`. We find the list of prime divisors of `n` and call it `D`. We then iterate through the list and check whether `n` is divisable by each element and `n` is divisable by each element squared. If both conditions are satisfied, we increment a counter. After iterating through list, we retrieve the total count and test whether the count is the same as the length of the list of divisors. If it is, then the number is a Powerful Number.

The ungolfed version is simpler to understand:

```
(define (f n)
  (let ([D (prime-divisors n)])
    (= (count (lambda (p)
                (and (divides? p n)
                     (divides? (sqr p) n)))
              D)
       (length D))))

```

*Have a wonderful weekend ahead!*

# Answer
> 2 votes
# Japt, 7 bytes

```
k e@vX²

```

Try it here

# Answer
> 2 votes
# JavaScript, 32 bytes

A port of xnor's solution to JavaScript:

```
f=(n,c=1)=>c**n%n?f(n,c+1):n/c%c

```

# Answer
> 2 votes
# Thunno 2 `G`, 2 bytes

```
ḟḅ

```

Try it online! or verify the first few powerful numbers

Port of Unrelated String's Jelly answer. Output with inverted booleans. Add the `!` flag to take the logical NOT.

#### Explanation

```
    # Implicit input
ḟ   # Get the list of prime factor exponents
 ḅ  # Check for each if it equals one
    # Take the maximum of this list
    # Implicit output

```

# Answer
> 2 votes
# Brachylog, 8 bytes

```
Ċ^₂ʰ^₃ᵗ×

```

Try it online!

Takes input as the Output variable. Outputs `true.` or `false.` as you would expect.

### Explanation

It’s just a description of the alternative definition.

```
Ċ          Take a couple of 2 variables
 ^₂ʰ       Square the first one
    ^₃ᵗ    Cube the last one
       ×   Multiply them: it must be equal to the given input
           Brachylog will implicitly check if such a couple of variables Ċ exists

```

# Answer
> 2 votes
# Ruby `-rprime`, 32 bytes

`Prime.prime_division` returns a number's prime factors \\$\prod\_{k=1}^\infty {p\_k}^{e\_k}\\$ in the form `[ [p1, e1], [p2, e2], ... ]` so this function checks whether every exponent is 2 or more.

```
->n{n.prime_division.all?{_2>1}}

```

Attempt This Online!

# Answer
> 2 votes
# Mathematica, ~~40~~ ~~39~~ ~~38~~ ~~36~~ 27 bytes

```
FactorInteger@#1∨#==1&

```

The first  is `\[VectorGreater]`, the second  is `\[Or\]`. Assuming UTF-8 encoding, they both occupy 3 bytes.

Try this online!

# Answer
> 2 votes
# APL(NARS), 8 chars

```
1∊≢¨⊂⍨π⎕

```

It return `0` if the number is as question ask, `1` otherwise. It is read in reverse `⎕π⍨⊂¨≢∊1` Call for input,`π` return the list of factors of input, `⍨⊂` doing partition as inputinput,`¨≢` for each element list, of partition return the lenght,`∊1` see if in the last list there is 1

test:

```
      1∊≢¨⊂⍨π⎕
⎕:
      36
0
~
      a/⍨∼{1∊≢¨⊂⍨π⍵}¨a←⍳100
┌14─────────────────────────────────────┐
│ 1 4 8 9 16 25 27 32 36 49 64 72 81 100│
└~──────────────────────────────────────┘

```

# Answer
> 2 votes
# Regex (ECMAScript or better), 50 bytes

```
^((?=(xx+?)\2+$)((?=\2+$)(?=(x+)(\4+$))\5){2,})*x$

```

Try it online! \- ECMAScript
Try it online! \- Perl
Try it online! \- Java
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- PCRE
Try it online! \- .NET

I adapted this on 2018-12-26, as a slight modification to the regex that matches numbers of the form \\$n^k\\$, where \\$k\\$ is a constant. In its implementation, that regex actually matches numbers that are either \\$0\\$ or of the form \\$n^k=\prod\_{i=0}^{q} p\_i^{k\_i}=p\_0^{k\_0}p\_1^{k\_1}p\_2^{k\_2}...p\_q^{k\_q}\\$ where all \\$p\_m\\$ are distinct primes, all \\$k\_m=k\\$, and \\$q\ge 0\\$.

The only changes here, to match powerful numbers instead, are to make \\$k\_m\ge 2\\$ (which takes 1 extra byte), and not to match \\$0\\$ (which saves 1 byte).

In other words, this regex works by dividing away each prime factor, from smallest to largest, asserting along the way that each distinct prime is divided away at least twice, with an end result of \\$1\\$.

```
^                     # N = input number (initial value of tail)
(                     # Loop/iterate the following:
    (?=(xx+?)\2+$)        # \2 = smallest prime factor of tail
    (                     # Loop/iterate the following:
        (?=\2+$)              # Assert tail is still divisible by \2
        (?=(x+)(\4+$))        # \4 = largest proper divisor of tail
                                   = tail / \2 (implicitly);
                              # \5 = tail - \4 (a tool to make tail = \4)
        \5                    # tail -= \5, i.e. tail = \4
    ){2,}                 # Iterate the above at least 2 times
)*                    # Iterate the above any number of times, minimum 0
x$                    # Assert tail == 1

```

# Retina 0.8.2, 56 bytes

```
.+
$*
^((?=(11+?)\2+$)((?=\2+$)(?=(1+)(\4+$))\5){2,})*1$

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 64 bytes

```
.+
$*
^((.){2,})(?<!^\3+(..+))\1*$(?<!^\4*(?(2)$)(((?<-2>)\1)+))

```

Try it online! Link includes test cases. Outputs `0` for a powerful number, `1` if not. Explanation:

```
.+
$*

```

Convert to unary.

```
^((.){2,})

```

Search for a nontrival integer...

```
(?<!^\3+(..+))

```

... that is not composite...

```
\1*$

```

... and is a factor of the input...

```
(?<!^\4*(?(2)$)(((?<-2>)\1)+))

```

... and whose square is not a factor of the input.

# Answer
> 1 votes
# Charcoal, 25 bytes

```
Ｎθ⊙…·²θ∧∧¬﹪θι﹪θ×ιι⬤…²ι﹪ιλ

```

Try it online! Link is to verbose version of code. Outputs an inverted Charcoal boolean, i.e. `-` if the input is not a powerful number, nothing if it is. Explanation:

```
Ｎθ                          Input as an integer
   …·                       Inclusive range from
     ²                      Literal integer `2` to
      θ                     Input integer
  ⊙                         Any value satisfies
           θ                Input integer
         ¬﹪                 Is divisible by
            ι               Current value
        ∧                   Logical And
              θ             Input integer
             ﹪              Is not divisible by
               ×ιι          Current value squared
       ∧                    Logical And
                   …        Range from
                    ²       Literal integer `2` to
                     ι      Current value
                  ⬤         All satisfy
                       ι    Outer value
                      ﹪     Is not divisible by
                        λ   Inner value
                            Implicitly print

```

# Answer
> 1 votes
# Desmos, 47 bytes

```
f(k)=0^{∏_{n=1}^{k^{.5}}mod((k/n^2)^{1/3},1)}

```

In case it bothers anyone, `k/n^2` can't be shortened to `k/nn` because `k/nn` is parsed as `k/n * n` when we actually want `k/(n*n)`.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Perl 5 `-ap`, 43 bytes

```
//&map$\+=$_**2*$'**3=="@F",@;for@;=1..$_}{

```

Try it online!

# Answer
> 1 votes
# Vyxal `g`, 23 bitsv2, 2.875 bytes

```
∆Ǐċ

```

Try it Online!

Bitstring:

```
00010101110001100111100

```

Prime exponents, check if not equal to one, minimum of that list (will always be greater than one for a powerful number)

# Answer
> 1 votes
# Uiua SBCS, 8 bytes

```
∊1⊜⧻.°/×

```

Try it!

Swaps falsy and truthy

---
Tags: code-golf, decision-problem, number-theory, integer, primes
---


title: Consecutive Composite Numbers

text:
# Question
Title: Consecutive Composite Numbers
# Challenge

Generate \\$n-1\\$ **consecutive** composite numbers using this prime gap formula

$$n!+2,n!+3,...,n!+n$$

**Input**

An integer \\$n\\$ such that \\$3 \leq n \leq 50 \\$.

**Output**

Sequence of \\$n-1\\$ consecutive composite numbers.

# Example

**Input**

```
3

```

**Output**

```
8
9

```

# Rules

* Output should be in integer format.

# Test Cases

For \\$n \> 20\\$, the results are very BIG integers (greater than 64-bits) and will most likely require a language that natively supports large numbers or a 3rd party library to handle them.

| n | \\$n-1\\$ consecutive composites |
| --- | --- |
| 3 | 8
9 |
| 5 | 122
123
124
125 |
| 21 | 51090942171709440002
51090942171709440003
51090942171709440004
51090942171709440005
51090942171709440006
51090942171709440007
51090942171709440008
51090942171709440009
51090942171709440010
51090942171709440011
51090942171709440012
51090942171709440013
51090942171709440014
51090942171709440015
51090942171709440016
51090942171709440017
51090942171709440018
51090942171709440019
51090942171709440020
51090942171709440021 |

# Answer
# Jelly, 3 bytes

```
Ḋ+!

```

**Try it online!**

A monadic Link that accepts a positive integer, \\$n\\$, and yields a list of the \\$n-1\\$ consecutive integers.

### How?

```
Ḋ+! - Link: integer, n
Ḋ   - dequeue {n}      -> [2, 3, 4, ..., n]
  ! - {n} factorial    -> n!
 +  - add (vectorises) -> [2+n!, 3+n!, 4+n!, ..., n+n!]

```
> 3 votes

# Answer
# APL(Dyalog Unicode), 5 bytes SBCS

```
1↓⍳+!

```

Try it on APLgolf!

A tacit function that takes an integer on the right and returns an array of n-1 composite numbers.

### Explanation

```
    ! ⍝ factorial
   +  ⍝ plus
  ⍳   ⍝ range
1↓    ⍝ drop the first

```

There are actually two other permutations of these five characters that produce the same result. See if you can find them. ;)

## 6 bytes, outputs full numbers under \\$10^{34}\\$

```
⍕1↓⍳+!

```

Try it! This requires adding `(⎕FR⎕PP)←1287 34` to the header to set the float and printing precision.
> 5 votes

# Answer
# Vyxal, 4 bytes

```
Ḣ?¡+

```

Try it Online!

```
Ḣ    # range(2, n+1)
   + # +
 ?¡  # n!

```
> 4 votes

# Answer
# Funge-98, 29 bytes

```
"HTMI"4(&:F2+v
\I_@#:-2\I.: <

```

Try it online!
> 4 votes

# Answer
# Python, 51 bytes

```
f=lambda n:range((n<2or(f(n-1).stop-n)*n)-~n)[1-n:]

```

Attempt This Online!

Returns a `range` object.

### Original Python, 56 bytes

```
f=lambda n:[n*([*f(n-1),3][0]-2)+j+2for j in range(n-1)]

```

Attempt This Online!
> 4 votes

# Answer
# JavaScript (Node.js), ~~52 51 47 46 45~~ 44 bytes

```
f=(n,i=n)=>--n&&f(n,g=i*n)>console.log(n-~g)

```

Try it online!

-1 byte from Arnauld/tsh

# JavaScript (Node.js), 38 bytes by Mukundan314

```
f=(n,i=n)=>--n?[...f(n,g=i*n),n-~g]:[]

```

Try it online!
> 3 votes

# Answer
# Jelly, 4 bytes

```
RḊ+!

```

Try it online!

Port of Vyxal answer.

-1 byte thanks to @emanresu A

Explanation:

```
RḊ+!
RḊ    # [2 .. n]
  +!  # + n!

```

Created with the help of Luminespire.
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
L¦¤!+

```

Try it online or verify all test cases.

**Explanation:**

```
L      # Push a list in the range [1, (implicit) input]
 ¦     # Remove the first value to make the range [2,input]
  ¤    # Push the last item (without popping the list): the input
   !   # Take its factorial
    +  # Add it to each value in the list
       # (after which this list is output implicitly as result)

```
> 3 votes

# Answer
# MathGolf, 5 bytes

```
╒╞\!+

```

Try it online.

**Explanation:**

```
╒      # Push a list in the range [1, (implicit) input]
 ╞     # Remove the first value to make the range [2,input]
  \    # Swap to push the (implicit) input
   !   # Take its factorial
    +  # Add it to each value in the list
       # (after which the entire stack is output implicitly as result)

```
> 3 votes

# Answer
# Desmos, 10 bytes

```
[2...n]+n!

```

Try it in Desmos!

The simplest a solution can get, to be honest.
> 3 votes

# Answer
# Perl 5, 41 bytes

```
sub{@a=1..pop;$"='*';map$_+1+eval"@a",@a}

```

Try it online!
> 2 votes

# Answer
# JavaScript (V8), 46 bytes

Prints the results in reverse order.

```
n=>{for(p=i=n;--i;)p*=i;while(--n)print(p-~n)}

```

Try it online!

---

# JavaScript (ES11), 52 bytes

With BigInts.

```
n=>{for(p=i=n;--i;)p*=i;while(--n)console.log(p-~n)}

```

Try it online!
> 2 votes

# Answer
# , 7 bytes

```
!-<:$i:

```

Attempt This Online!

Returns the list of numbers in reverse order. When given a bigint, outputs the exact numbers in bigint.

```
!-<:$i:    input: n, a positive integer
     i:    [-n, -n+1, ..., n]
  <:       n-1
    $      take first n-1 items from the list, i.e. [-n, ..., -2]
!          n!
 -         n! - each item of [-n, ..., -2]
           == [n!+n, n!+n-1, ..., n!+2]

```

# , 8 bytes

```
!+-.{.i:

```

Attempt This Online!

Returns the list of numbers in the order given.

```
!+-.{.i:    input: n, a positive integer
      i:    [-n, -n+1, ..., n]
  -.        1-n
    {.      since 1-n is negative, take n-1 items from the end;
            [2, ..., n]
!+          add n! to each item of the list

```
> 2 votes

# Answer
# Uiua SBCS, 9 bytes

```
↘1+/×.+1⇡

```

Try it!
> 2 votes

# Answer
# Python 3.8 (pre-release), ~~69~~ 62 bytes

```
lambda n:[i-~math.factorial(n)for i in range(1,n)]
import math

```

Try it online!

Edit: changed `math.prod` to `math.factorial`, thanks to @l4m2
> 2 votes

# Answer
# dc, ~~56~~ 54 bytes

```
[dlf*sf1-d0!=q]sq1sf?d1-sm[dlf2++p0=m1+dlm!=e]selqxlex

```

Try it online!

This solution isn't the most optimized, you could probably use less registers than I did here.
> 2 votes

# Answer
# Google Sheets, 32 bytes

```
=SORT(FACT(A1)+SEQUENCE(A1-1)+1)

```
> 2 votes

# Answer
# C (gcc), 170 bytes

Using The GNU Multiple Precision Arithmetic Library

```
f(n){mpz_t f,t;mpz_init(f);mpz_init(t);mpz_set_ui(f,1);for(int i=1;i<=n;mpz_mul_ui(f,f,i++));for(int i=2;i<=n;mpz_add_ui(t,f,i),mpz_out_str(stdout,10,t),puts(""),i++);}

```

Try it online!
> 1 votes

# Answer
# Scala 3, 55 bytes

```
n=>{val a=(1 to n).map(BigInt(_));a.map(_+1+a.product)}

```

Attempt This Online!
> 1 votes

# Answer
# PARI/GP, 15 bytes

```
n->[n!+2..n!+n]

```

Attempt This Online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 13 bytes

```
#!+2~Range~#&

```

Try it online!
> 1 votes

# Answer
# Retina, 43 bytes

```
.+
*
v`__+
$.&$*
L$`\d+
$$.($&*_$=
%~`^
.+¶

```

Try it online! Outputs the numbers in descending order. Explanation:

```
.+
*

```

Convert `n` to unary.

```
v`__+
$.&$*

```

Create an expression `n*...*3*2*` that evaluates to `n!` in unary.

```
L$`\d+
$$.($&*_$=

```

For each integer in that expression, create an expression that adds `i` and converts to decimal.

```
%~`^
.+¶

```

Evaluate each resulting expression.
> 1 votes

# Answer
# Charcoal, 11 bytes

```
≔…·²ＮθＩ⁺θΠθ

```

Try it online! Link is to verbose version of code.

```
≔…·²Ｎθ

```

Create a list from `2` up to `n` inclusive.

```
Ｉ⁺θΠθ

```

Vectorised add the list to its product.

Of course, the given formula is just an existence proof and there are usually lower runs. For instance, the LCM is readily proven to produce a run:

```
Ｎθ≔…·²θηＷ⌈﹪±θη≧⁺ιθＩ⁺θη

```

Try it online! Link is to verbose version of code. Or more efficiently:

```
Ｎθ≔…·²θηＦη≔⌊Φ×⊖ηθ¬﹪κιθＩ⁺θη

```

Try it online! Link is to verbose version of code.
> 1 votes

# Answer
# Java 10, ~~134~~ 131 bytes

```
n->{var f=n.ONE;int N=n.intValue(),i=N;for(;i>1;)f=f.multiply(n.valueOf(i--));for(;i++<N;)System.out.println(f.add(n.valueOf(i)));}

```

-3 bytes thanks to *@ceilingcat*.

Input as a `BigInteger`, outputs on separated lines to STDOUT.

Try it online.

**Explanation:**

```
n->{                            // Method with BigInteger as parameter and no return:
  var f=n.ONE;                  //  Start `f` with BigInteger 1
  int N=n.intValue(),           //  Set `N` to the input-BigInteger as integer
  i=N;for(;i>1;)                //  Loop `i` in the range [N,1):
    f=f.multiply(n.valueOf(i)); //   Multiply `f` by `i`
  for(;i++<N;)                  //  Loop `i` again, this time in the range (1,N]:
    System.out.println(         //   Print with trailing newline:
      f.add(n.valueOf(i)));}    //    `f` + `i`

```
> 1 votes

# Answer
# Labyrinth, 30 bytes

```
?:}  @\!
 (:{+ ""
*; :=;;
#(;)

```

Try it online!

Introducing "small-loop-oriented programming" ;)

```
?    program start; take n from stdin
     let's say n = 4
     [ 4 | ]

:}   run in the order of :(:}
(:   : dup               [ 4 4 | ]
     ( decrement         [ 4 3 | ]
     : dup               [ 4 3 3 | ]
     } move to aux.stack [ 4 3 | 3 ]
     loop until the top is 0 after `decrement`
     [ 4 3 2 1 0 | 1 2 3 ]

*;   run in the order of ;*#(
#(   ; drop         [ 4 3 2 1 | 1 2 3 ]
     * mul          [ 4 3 2 | 1 2 3 ]
     # stack height [ 4 3 2 3 | 1 2 3 ]
     ( decrement    [ 4 3 2 2 | 1 2 3 ]
     loop until the top is 0 after `decrement`, i.e. stack height is 1
     [ 24 0 | 1 2 3 ]

;)   drop 0, and increment the factorial
     [ 25 | 1 2 3 ]

{+   run in the order of :=+{
:=   : dup                 [ 25 25 | 1 2 3 ]
     = swap the tops       [ 25 1 | 25 2 3 ]
     + add                 [ 26 | 25 2 3 ]
     { move from aux.stack [ 26 25 | 2 3 ]
     loop until the top is 0 after `swap the tops`
     [ 26 27 28 25 0 | 25 ]

;;   drop twice [ 26 27 28 | 25 ]

\!   run in the order of ""!\  (" is no-op)
""   ! pop and print as num
     \ print a newline
     loop until the top is zero, i.e. there is nothing left to print

@    end the program

```
> 1 votes

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