Given a number n >= 2, output all the positive integers less than n where gcd(n, k) == 1 (with k being any one of the output numbers).  Numbers of this sort are coprime to each other.

Example: 10 gives the output [1, 3, 7, 9] (in any form you like, as long as the numbers are unambiguously separated and in some sort of list). The list cannot have duplicate entries and doesn't have to be sorted.

More test cases:

2 -> [1]
3 -> [1, 2]
6 -> [1, 5]
10 -> [1, 3, 7, 9]
20 -> [1, 3, 7, 9, 11, 13, 17, 19]
25 -> [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24]
30 -> [1, 7, 11, 13, 17, 19, 23, 29]

We are also not counting numbers above n that are coprime to n, solely because I'm fairly certain there's infinite solutions.

Also note: Numbers that are coprime to each other are also said to be relatively prime or mutually prime to each other.

share|improve this question
    
Do seperate strings (e.g. 1\n3\n) count as valid output? – devRicher 6 hours ago
    
@devRicher that works, sure. – Easterly Irk 5 hours ago

21 Answers 21

Python 2, 61 47 bytes

lambda n:[k/n for k in range(n*n)if k/n*k%n==1]

Try it online!

Background

Consider the ring (Zn, +n, ·n). While this ring is usually defined using residue classes modulo n, it can also be thought of as the set Zn = {0, ..., n - 1}, where the addition and multiplication operators are defined by a +n b = (a + b) % n and a ·n b = a · b % n, where +, ·, and % denote the usual addition, multiplication, and modulo operators over the integers.

Two elements a and b of Zn are called mutual multiplicative inverses modulo n if a ·n b = 1 % n. Note that 1 % n = 1 whenever n > 1.

Fix n > 1 and let a be a coprime of n in Zn. If a ·n x = a ·n y for two elements x and y of Zn, we have that a · x % n = a · y % n. This implies that a · (x - y) % n = a · x % n - a · y % n = 0, and we follow that n | a · (x - y), i.e., n divides a · (x - y) evenly. Since n shares no prime divisors with a, this means that n | x - y. Finally, because -n < x - y < n, we conclude that x == y. This shows that the products a ·n 0, …, a ·n (n - 1) are all different elements of Zn. Since Zn has exactly n elements, one (and exactly one) of those products must be equal to 1, i.e., there is a unique b in Zn such that a ·n b = 1.

Conversely, fix n > 1 and let a be an element of Zn that is not coprime to n. In this case, there is a prime p such that p | a and p | n. If a admitted a multiplicative inverse modulo n (let's all it b), we'd have that a ·n b = 1, meaning that a · b % n = 1 and, therefore, (a · b - 1) % n = a · b % n - 1 = 0, so n | a · b - 1. Since p | a, we follow that p | a · b. On the other hand, since p | n, we also follow that p | a · b - 1. This way, p | (a · b) - (a · b - 1) = 1, which contradicts the assumption that p is a prime number.

This proves that the following statements are equivalent when n > 1.

  • a and n are coprime.

  • a admits a multiplicative inverse modulo n.

  • a admits a unique multiplicative inverse modulo n.

How it works

For each pair of integers a and b in Zn, the integer k := a · n + b is a unique; in fact, a and b are quotient and remainder of k divided by n, i.e., given k, we can recover a = k / n and b = k % n, where / denotes integer division. Finally, since a ≤ n - 1 and b ≤ n - 1, k is an element of Zn2; in fact, k ≤ (n - 1) · n + (n - 1) = n2 - 1.

As noted above, if a and n are coprime, there will be a unique b such that a · b % n = 1, i.e., there will be a unique k such that k / n = a and k / n · k % n = (k / n) · (k % n) % n = 1, so the generated list will contain a exactly once.

Conversely, if a and n are not coprime, the condition k / n · k % n = 1 will be false for all values of k such that a = k / n, so the generated list will not contain a.

This proves that the list the lambda returns will contain all of n's coprimes in Zn exactly once.

share|improve this answer
7  
"GCD? Where we're going, we don't need GCD." – Easterly Irk 11 hours ago
    
Amazing Dennis. This is truly amazing. And you meant to put instead of n2, right? – Zachary T 3 hours ago
    
@ZacharyT Indeed, but I was missing an / in the previous superscript. Thanks for catching that. – Dennis 3 hours ago

Jelly, 4 bytes

gRỊT

Try it online!

How it works

gRỊT  Main link. Argument: n

 R    Range; yield [1, ..., n].
g     Compute the GCD of n and each k in [1, ..., n].
  Ị   Insignificant; return 1 for GCDs less or equal to 1.
   T  Truth; yield the indices of all truthy elements.
share|improve this answer
12  
Coding in this language takes some gRỊT – ETHproductions 12 hours ago

Python, 93 82 74 bytes

f=lambda a,b:f(b,a%b)if b else a<2
lambda c:[i for i in range(c)if f(i,c)]

f recursively checks for coprime-ness, and the second lambda generates them. Outputs a list.

share|improve this answer

Mathematica, 25 bytes

Range@#~GCD~#~Position~1&

Slightly weird output format, where each result is wrapped in a separate list, e.g. {{1}, {3}, {7}, {9}}. If that's not okay, I've got two solutions at 30 bytes:

Select[Range[x=#],#~GCD~x<2&]&
#&@@@Range@#~GCD~#~Position~1&

Mathematica actually has CoprimeQ but that's way too long.

share|improve this answer
    
What does Q mean in CoprimeQ? – Conor O'Brien 14 mins ago

2sable, 4 bytes

Code:

ƒN¿–

Explanation:

ƒ       # For N in the range [0, input]..
 N¿     #   Compute the GCD of N and the input
   –    #   If 1, print N with a newline

Uses the CP-1252 encoding. Try it online!

share|improve this answer

MATLAB/Octave, 22 bytes

@(n)find(gcd(1:n,n)<2)

Try it online!

share|improve this answer

JavaScript (ES6), 64 61 bytes

Saved 3 bytes thanks to @user81655

n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

Test snippet

f=n=>[...Array(n).keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n))

for(var i = 2; i < 50; i++) console.log(i + ":", `[${ f(i) }]`);

share|improve this answer
    
Can't you swap a== with a<2? – Easterly Irk 12 hours ago
    
@EasterlyIrk Not sure, a might be 0 at some point. I'll have to check – ETHproductions 12 hours ago
    
You could move the GCD function into the filter to remove the need to receive a b parameter: ...keys()].filter(b=>(g=a=>b?g(b,b=a%b):a<2)(n)) – user81655 5 hours ago
    
@user81655 That's great, thanks! :-) – ETHproductions 5 hours ago

MATL, 7 bytes

:GZd1=f

Try it online!

share|improve this answer

Actually, 8 bytes

;╗R`╜┤`░

Try it online!

Explanation:

;╗R`╜┤`░
  R`  `░  elements of range(1, n+1) where
;╗  ╜     n and the element
     ┤    are coprime
share|improve this answer
1  
I believe you can just do range(1, n) if that saves any bytes. – ETHproductions 11 hours ago
    
@ETHproductions It doesn't. The two options are R (range(1, n+1)) and r (range(n)). Since they're equivalent, I chose R (since I accidentally hit caps lock while writing the code). – Mego 11 hours ago
    
Yeah, that's what I figured. I didn't see an instruction that seemed dedicated to incrementing, but I thought there might have been one anyway – ETHproductions 11 hours ago

CJam, 14 bytes

{:X{Xmff%:*},}

Try it online!

Explanation

We don't need to check all possible divisors of a and b to test whether they're coprime. It's sufficient to look at whether any of the prime factors of b divides a.

:X     e# Store the input in X.
{      e# Filter the list [0 1 ... X-1] by the results of this block...
  Xmf  e#   Get the prime factors of X.
  f%   e#   Take the current value modulo each of those prime factors.
  :*   e#   Multiply the results. Iff any of them divide the current
       e#   value, there's a 0 in the list, and the result of the product
       e#   is also 0, dropping the value from the resulting list.
},
share|improve this answer

Jellyfish, 19 18 bytes

p
[#
`B
&~xr1
NnEi

This works by computing the prime factors of all numbers in the range and checking whether they intersect that of the input (Jellyfish doesn't have a gcd builtin yet). For golfing reasons, the output is in descending order. Try it online!

Detailed explanation to come later.

share|improve this answer

Mathematica, 33 bytes

xSelect[Range@x,x~CoprimeQ~#&]

Contains U+F4A1

share|improve this answer
    
What's the unprintable do? – Easterly Irk 12 hours ago
2  
@EasterlyIrk introduces an unnamed function with a named argument. it's rendered as an arrow in Mma. – Martin Ender 12 hours ago
    
@MartinEnder oh, cool. – Easterly Irk 12 hours ago
    
U+F4A1 is a private use character. As Martin said, it's rendered as an arrow in Mathematica. – Zachary T 12 hours ago

Stacked, noncompeting, 24 21 bytes

Saved 3 bytes, inspired by Borsunho's ruby. (1 eq to 2<)

{!n:>1+:n gcd 2<keep}

Try it here!

This is an n-lambda that takes a single argument and yields the array.

{!n:>1+:n gcd 2<keep}
{!                  }  n-lambda
  n                    push n
   :>                  range [0, n)
     1+                range [1, n]
       :               duplicate
        n gcd          element-wise gcd with n
              2<       element-wise equality with 1
                       this yields the range [1, n] and a boolean mask of coprime numbers
                keep   then, we simply apply the mask to the range and keep coprimes.
share|improve this answer
    
Why is this noncompeting? – Zachary T 11 hours ago
    
@ZacharyT mainly, keep wasn't working nicely. – Conor O'Brien 11 hours ago

Ruby, 3634

->n{n.times{|i|p i if i.gcd(n)<2}}

Admittedly, this isn`t a very inspired answer.

2 bytes saved thanks to Conor O'Brien.

share|improve this answer
    
You can shave off two bytes by removing parentheses around (n) – Conor O'Brien 11 hours ago

Python 3, 60 bytes

Imports gcd instead of writing a new lambda for it. Golfing suggestions welcome. Try it online!

import math
lambda c:[i for i in range(c)if math.gcd(c,i)<2]
share|improve this answer
    
I don't think you can golf this more. Importing gcd directly or math as m both add bytes. – Easterly Irk 11 hours ago

Dyalog APL (v16), 6 bytes / APL, 10 bytes.

⍸1=⊢∨⍳

This won't work on TryAPL. Explanation (input n):

⍸1=⊢∨⍳
⊢∨⍳ - gcd(1,n) .. gcd(n,n)
1=  - Element wise equality with 1.
⍸   - Truthy indexes.

Old solution that works on TryAPL:

0~⍨⍳×1=⊢∨⍳

Explanation (input n):

0~⍨⍳×1=⊢∨⍳
         ⍳ - 1 ... n (Thus, ⎕IO is 1)
       ⊢∨  - Each GCD'd by n
     1=    - Test equality with 1 on each element
   ⍳×      - multiplied by its index
0~⍨        - without 0.
share|improve this answer
3  
I love the way APL code looks like the face you make when you read it. – DJMcMayhem 12 hours ago
    
Yep, and it demolishes almost every not code-golf-oriented language. :). – Zachary T 11 hours ago
    
Why only "might" work? – Easterly Irk 11 hours ago
    
I'm just going to assume it works. – Zachary T 11 hours ago
    
@ZacharyT why can't you test it? When I paste it into try-apl.org, it errors with invalid token. – Easterly Irk 11 hours ago

Haskell, 27 bytes

f n=[k|k<-[1..n],gcd n k<2]

Try it online!

share|improve this answer

memes, 11 bytes non-competing

Non-competing as iteration of STDIN is new. Uses UTF-8 encoding.

d`}}]i=1?ip

Explanation:

d     Set program to not output result
`}    Loop next input-times
}]i   GCD of input and loop index
=1?   Is it equal to 1? If yes,
ip    Print out loop index

} accesses the next input item, but last input is looped through when given, so inputting 6 will result as 6 6 6 6 6 ... in STDIN, making it possible for reading two outputs from one.

share|improve this answer
    
Did you just create this lang today? If it's made before the challenge, it has to be non-competing. – Easterly Irk 8 hours ago
    
@EasterlyIrk It was made 3 days ago, im just constantly working on it. Also, I assume you mean after? – devRicher 8 hours ago
    
Yeah, typo thanks. And it's okay, as long as the features used in the answer and older than the challenge. – Easterly Irk 8 hours ago
    
@EasterlyIrk I see, in that case i'll have to edit my answer. – devRicher 8 hours ago
    
Yeah, sorry. :/ – Easterly Irk 8 hours ago

Perl 6, 20 bytes

{grep 2>* gcd$_,^$_}
share|improve this answer

Wonder, 35 bytes

@(!>@=1len inx 'fac#0fac#1).'rng1#0

Usage:

(@(!>@=1len inx 'fac#0fac#1).'rng1#0)3

Basically filters over a range from 1 to the input with a predicate:

  • Find all factors of both the current mapped item and the input.
  • Find the intersection of both arrays.
  • Check if the result is of length 1. If the 2 numbers are coprime, then their factors' intersection set should only contain 1.
share|improve this answer

Mathematica, 26 bytes

Pick[r=Range@#,r~GCD~#,1]&
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.