Coprimes up to N

51

3

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.

Rɪᴋᴇʀ

Posted 2016-12-26T18:00:02.387

Reputation: 7 410

Do seperate strings (e.g. 1\n3\n) count as valid output? – devRicher – 2016-12-27T00:37:47.547

@devRicher that works, sure. – Rɪᴋᴇʀ – 2016-12-27T00:53:00.093

The intuition about there being an infinite number of numbers above n that are coprime to n feels correct to me. There are infinitely many primes, and a prime would be coprime with every number below it. Therefore, every prime greater than n (of which there are infinitely many) are also part of the coprime list. – Brian J – 2016-12-27T20:28:46.977

@BrianJ Not just that. If c and n are coprimes, c + kn and n are also coprimes, for all integers k. – Dennis – 2016-12-28T02:12:51.947

1

Fun fact: these are called totatives.

– Wojowu – 2016-12-29T15:20:01.877

Answers

17

Jelly, 3 bytes

gÐṂ

Try it online!

How does this work?

gÐṂ  - (Monadic) Full program.

g    - Greatest common divisor.
 ÐṂ  - Keep the elements with minimum link value (i.e. those with GCD == 1)
       Note that this automatically creates the range [1, input] (inclusive).

Proof of validity

Since we want to extract the coprimes only, the minimum value of the Greatest-Common-Divisors list has to be 1 for the ÐṂ trick to work. Let's prove that (in two different methods):

  1. The implicitly generated range, \$[1, \text{input}]\$ contains \$1\$ and \$\gcd(1, x) = 1\:\:\forall\:\:x \in \mathbb{Z}^{*}\$. The greatest common divisor is always a strictly positive integer, hence \$1\$ is guaranteed to occur and will always be the minimum value.

  2. Two consecutive positive integers are always coprime. Consider \$x, y \in \mathbb{Z}^{*}\$, with \$y = x + 1\$. Then we take another positive integer \$k\$ such that \$k \mid x\$ and \$k \mid y\$.

    This implies that \$k \mid (y - x)\$, so \$k \mid (x + 1 - x)\$, thus \$k \mid 1\$. The only positive integer to divide \$1\$ is \$1\$ itself, so it is guaranteed to appear in the list and will always be the minimum value.

Mr. Xcoder

Posted 2016-12-26T18:00:02.387

Reputation: 39 774

2You outgolfed Dennis in his own language after 9 months! – Adám – 2017-09-28T19:21:10.603

@Adám I am not sure whether ÐṂ existed back then, anyway I am quite satisfied with this one. – Mr. Xcoder – 2017-09-28T19:22:03.417

2

For the record, DṂ did exist, but it only worked for monads. The commit implemented Þ, ÐṂ, ÐṀ for dyads is dated May 9, 2017.

– Dennis – 2017-09-28T21:31:44.700

@Dennis I knew there'd be a good reason why you didn't have the 3-byte version. We were wondering about that in chat too, so thanks for the useful information! – Mr. Xcoder – 2017-09-29T04:21:30.790

57

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 \$(Z_n, +_n, \cdot_n)\$. While this ring is usually defined using residue classes modulo \$n\$, it can also be thought of as the set \$Z_n = \{0, \dots, n - 1\}\$, where the addition and multiplication operators are defined by \$a +_n b = (a + b)\:\%\: n\$ and \$a \cdot_n b = a \cdot b\:\%\: n\$, where \$+,\:\cdot\text{, and } \%\$ denote the usual addition, multiplication, and modulo operators over the integers.

Two elements \$a\$ and \$b\$ of \$Z_n\$ are called mutual multiplicative inverses modulo \$n\$ if \$a \cdot_n b = 1\:\%\:n\$. Note that \$1\:\%\:n = 1\$ whenever \$n > 1\$.

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

Conversely, fix \$n > 1\$ and let \$a\$ be an element of \$Z_n\$ that is not coprime to \$n\$. In this case, there is a prime \$p\$ such that \$p \mid a\$ and \$p \mid n\$. If \$a\$ admitted a multiplicative inverse modulo \$n\$ (let's call it \$b\$), we'd have that \$a \cdot_n b = 1\$, meaning that \$a \cdot b\:\%\:n = 1\$ and, therefore, \$(a \cdot b - 1)\:\%\:n = a \cdot b\:\%\:n - 1 = 0\$, so \$n \mid a \cdot b - 1\$. Since \$p \mid a\$, we follow that \$p \mid a \cdot b\$. On the other hand, since \$p \mid n\$, we also follow that \$p \mid a \cdot b - 1\$. This way, \$p \mid (a \cdot b) - (a \cdot 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 \$Z_n\$, the integer \$k := a \cdot n + b\$ is 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 \$Z_{n^2}\$; in fact, \$k ≤ (n - 1) \cdot n + (n - 1) = n^2 - 1\$.

As noted above, if \$a\$ and \$n\$ are coprime, there will be a unique \$b\$ such that \$a \cdot b\:\%\:n = 1\$, i.e., there will be a unique \$k\$ such that \$k / n = a\$ and \$k / n \cdot k\:\%\:n = (k / n) \cdot (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 \cdot 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 \$Z_n\$ exactly once.

Dennis

Posted 2016-12-26T18:00:02.387

Reputation: 196 637

26"GCD? Where we're going, we don't need GCD." – Rɪᴋᴇʀ – 2016-12-26T19:31:31.043

1Woah. That's all I wanted to write, but apparently I needed 15 characters. Still, woah. Great job. – Eric Lagergren – 2016-12-27T08:30:02.533

24

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.

Dennis

Posted 2016-12-26T18:00:02.387

Reputation: 196 637

34Coding in this language takes some gRỊT – ETHproductions – 2016-12-26T18:33:25.593

1

I managed to (ab)use the "Minimum link value" quick (ÐṂ) in order to get 3 bytes.

– Mr. Xcoder – 2017-09-28T19:00:51.863

14

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.

Martin Ender

Posted 2016-12-26T18:00:02.387

Reputation: 184 808

1What does Q mean in CoprimeQ? – Conor O'Brien – 2016-12-27T06:33:01.583

2@ConorO'Brien "question" I guess. All decision problem built-ins end in Q like EvenQ, PrimeQ or SubsetQ. – Martin Ender – 2016-12-27T07:32:22.837

10

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 coprimes, and the second lambda generates them. Outputs a list.

Rɪᴋᴇʀ

Posted 2016-12-26T18:00:02.387

Reputation: 7 410

10

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!

Adnan

Posted 2016-12-26T18:00:02.387

Reputation: 41 965

Good job (almost) beating Dennis. (few minutes late though). – Zacharý – 2016-12-31T01:15:05.783

7

Actually, 8 bytes

;╗R`╜┤`░

Try it online!

Explanation:

;╗R`╜┤`░
  R`  `░  elements of range(1, n+1) where
;╗  ╜     n and the element
     ┤    are coprime

Mego

Posted 2016-12-26T18:00:02.387

Reputation: 32 998

1I believe you can just do range(1, n) if that saves any bytes. – ETHproductions – 2016-12-26T19:26:55.277

1@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 – 2016-12-26T19:27:38.857

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 – 2016-12-26T19:28:36.893

6

MATL, 7 bytes

:GZd1=f

Try it online!

James

Posted 2016-12-26T18:00:02.387

Reputation: 54 537

6

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) }]`);

ETHproductions

Posted 2016-12-26T18:00:02.387

Reputation: 47 880

Can't you swap a== with a<2? – Rɪᴋᴇʀ – 2016-12-26T18:14:11.383

@EasterlyIrk Not sure, a might be 0 at some point. I'll have to check – ETHproductions – 2016-12-26T18:25:48.730

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 – 2016-12-27T01:22:14.450

@user81655 That's great, thanks! :-) – ETHproductions – 2016-12-27T01:24:46.097

6

MATLAB/Octave, 22 bytes

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

Try it online!

flawr

Posted 2016-12-26T18:00:02.387

Reputation: 40 560

6

Jellyfish, 19 18 bytes

p
[#
`B
&~xr1
NnEi

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

Explanation

First off, i is evaluated input; for input 10, the value of the i-cell is 10.

r1
i

Here r (range) is applied to the input and 1. Because the input is greater than 1, the range is in descending order; for input 10, this gives [9 8 7 6 5 4 3 2 1].

[#
`B
&~x
Nn

This part is one big function, which is evaluated on i and the above range.

~x
n

Intersection (n) of prime factors (x).

&~x
Nn

Is it empty? (N)

`
&~x
Nn

Thread to level 0, testing for each element of the range.

[#
`B
&~x
Nn

Filter (#) the range with respect to this list of booleans. The function produced by [ wants to use the argument to # as its own argument, so we put a B to block # from getting any arguments. Otherwise, the value of the ~-cell would be used as the argument of the big function. Finally, p prints the result.

Zgarb

Posted 2016-12-26T18:00:02.387

Reputation: 39 083

5

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.

Conor O'Brien

Posted 2016-12-26T18:00:02.387

Reputation: 36 228

Why is this noncompeting? – Zacharý – 2016-12-26T19:16:20.103

@ZacharyT mainly, keep wasn't working nicely. – Conor O'Brien – 2016-12-26T19:17:09.017

5

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.
},

Martin Ender

Posted 2016-12-26T18:00:02.387

Reputation: 184 808

5

Mathematica, 26 bytes

Pick[r=Range@#,r~GCD~#,1]&

alephalpha

Posted 2016-12-26T18:00:02.387

Reputation: 23 988

1Ohhhh, I've been looking for something like Pick. I guess now I'm glad I didn't find it, though. ;) But it should be very useful for future challenges. – Martin Ender – 2016-12-27T08:27:10.987

4

Dyalog APL, 10 bytes.

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.

Zacharý

Posted 2016-12-26T18:00:02.387

Reputation: 5 710

3I love the way APL code looks like the face you make when you read it. – James – 2016-12-26T18:43:56.303

Yep, and it demolishes almost every not code-golf-oriented language. :). – Zacharý – 2016-12-26T18:47:34.413

Why only "might" work? – Rɪᴋᴇʀ – 2016-12-26T19:10:52.367

I'm just going to assume it works. – Zacharý – 2016-12-26T19:14:55.493

@ZacharyT why can't you test it? When I paste it into try-apl.org, it errors with invalid token. – Rɪᴋᴇʀ – 2016-12-26T19:16:20.820

This doesn't work on tryapl.org. – Conor O'Brien – 2016-12-26T19:18:30.120

I don't have Dyalog. – Zacharý – 2016-12-26T19:18:30.780

@ZacharyT You can test on try-apl.org. – Rɪᴋᴇʀ – 2016-12-26T19:19:38.710

It's v16. Won't work. – Zacharý – 2016-12-26T19:22:14.763

Those 6 characters are actually 14 bytes in UTF-8 or 12 bytes in UTF-16 (try 80⎕DR'⍸1=⊢∨⍳'). You may want to link to this.

– Adám – 2017-01-24T09:15:55.177

Thank's, I'll revert it to the old version to save 2 bytes. – Zacharý – 2017-01-25T12:08:09.577

There. It's changed to the 10 byte version. – Zacharý – 2017-01-25T12:09:30.327

@ZacharyT How did you even get a hold of version 16.0? – Adám – 2017-03-14T06:41:50.850

Ugh. I was being insane. Following your suggestion from a while back. Thinking it was released like an idiot. – Zacharý – 2017-03-15T13:56:15.063

4

Perl 6, 20 bytes

{grep 2>* gcd$_,^$_}

Sean

Posted 2016-12-26T18:00:02.387

Reputation: 4 136

4

Brachylog, 16 13 bytes

>.$p'(e:A*?),

This is a function that takes N as input, and generates all integers less than and coprime to it.

Try it online! As is often the case in Brachylog, this has had extra code added to make the function into a full program; Brachylog's interpreter, if given a function rather than a full program, will run it but not print the output, which means you can't really observe its workings.

Explanation:

A Brachylog program is a chain of constraints; typically, the LHS of one constraint is the RHS of the next.

>.$p'(e:A*?),
>              The input is greater than
 .             the output, whose
  $p           prime factorisation does
    '(     )   not obey the following constraint:
      e        it has an element which
       :A*     can be multiplied by something to
          ?    produce the input.
            ,  (This comma turns off an unwanted implicit constraint.)

Golfed down three characters by realising there's no reason to check to see if the common factor (which is already known to be a prime factor of the output) is a prime factor of the input. We already know it's prime, so we can just check if it's a factor. I'm pleasantly surprised here that :A*? doesn't send the interpreter into an infinite loop and doesn't allow a non-integer value for A, but as the interpreter does what I want, I'll take it.

user62131

Posted 2016-12-26T18:00:02.387

Reputation:

4

Japt -f, 9 8 5 2 bytes

jN

Try it

  • 2 bytes saved thanks to ETH pointing out a brainfart, which led to another byte saved.

Shaggy

Posted 2016-12-26T18:00:02.387

Reputation: 24 623

You could do o f_jU – ETHproductions – 2017-10-12T17:39:02.027

Thanks, @ETHproductions. Don't know what I was thinking here! Must've been one of those (many) moments when I forget j can also be used to test if 2 numbers are co-prime. – Shaggy – 2017-10-13T10:23:26.997

3

Mathematica, 33 bytes

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

Contains U+F4A1

JungHwan Min

Posted 2016-12-26T18:00:02.387

Reputation: 13 290

What's the unprintable do? – Rɪᴋᴇʀ – 2016-12-26T18:14:38.700

3@EasterlyIrk introduces an unnamed function with a named argument. it's rendered as an arrow in Mma. – Martin Ender – 2016-12-26T18:15:04.943

@MartinEnder oh, cool. – Rɪᴋᴇʀ – 2016-12-26T18:15:20.957

U+F4A1 is a private use character. As Martin said, it's rendered as an arrow in Mathematica. – Zacharý – 2016-12-26T18:18:45.977

3

Haskell, 27 bytes

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

Try it online!

flawr

Posted 2016-12-26T18:00:02.387

Reputation: 40 560

3

memes, 11 bytes non-competing, outdated

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.

devRicher

Posted 2016-12-26T18:00:02.387

Reputation: 1 609

Did you just create this lang today? If it's made before the challenge, it has to be non-competing. – Rɪᴋᴇʀ – 2016-12-26T22:16:02.980

@EasterlyIrk It was made 3 days ago, im just constantly working on it. Also, I assume you mean after? – devRicher – 2016-12-26T22:16:49.320

Yeah, typo thanks. And it's okay, as long as the features used in the answer and older than the challenge. – Rɪᴋᴇʀ – 2016-12-26T22:17:39.573

@EasterlyIrk I see, in that case i'll have to edit my answer. – devRicher – 2016-12-26T22:18:38.383

Yeah, sorry. :/ – Rɪᴋᴇʀ – 2016-12-26T22:18:49.493

@EasterlyIrk There were shorter answers anyways ;) – devRicher – 2016-12-26T22:19:11.673

3

Julia 0.5, 23 bytes

!n=1÷gcd.(1:n,n)|>find

Try it online!

Dennis

Posted 2016-12-26T18:00:02.387

Reputation: 196 637

3

05AB1E, 3 bytes

Lʒ¿

Try it online!

Has new features.

Erik the Outgolfer

Posted 2016-12-26T18:00:02.387

Reputation: 38 134

2

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.

Borsunho

Posted 2016-12-26T18:00:02.387

Reputation: 261

You can shave off two bytes by removing parentheses around (n) – Conor O'Brien – 2016-12-26T18:54:56.113

2

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]

Sherlock9

Posted 2016-12-26T18:00:02.387

Reputation: 11 664

I don't think you can golf this more. Importing gcd directly or math as m both add bytes. – Rɪᴋᴇʀ – 2016-12-26T19:05:58.797

2

Julia, 30 bytes

n->filter(x->(gcd(n,x)<2),1:n)

Anonymous function. filter removes elements from a list that aren't truthy according to a function.

In this case, the function is x->(gcd(n,x)<2) (true if the gcd of the input and the list element is less than 2). The list is the range 1:n.

Rɪᴋᴇʀ

Posted 2016-12-26T18:00:02.387

Reputation: 7 410

2

PARI/GP, 27 bytes

n->[k|k<-[1..n],gcd(k,n)<2]

This uses the set-notation introduced in version 2.6.0 (2013). In earlier versions, four more bytes were needed:

n->select(k->gcd(k,n)<2,[1..n])

would be needed.

Charles

Posted 2016-12-26T18:00:02.387

Reputation: 2 435

How does this work? – Rɪᴋᴇʀ – 2016-12-28T18:12:43.993

1@EasterlyIrk The same as most of these submissions -- make a range from 1 to n ([1..n]), check if gcd is 1 (gcd(n,k)<2), return the numbers with this property. The -> is function/closure notation, shorter by 2 bytes than normal function syntax and [...|...<-...,...] is the set notation explained in the answer (see section 2.3.14 in the User's Manual, or search for <-). – Charles – 2016-12-28T18:23:01.657

2

05AB1E, 4 bytes

GN¿–

Try it online!

How it works

     # implicit input
G    # for N in range(1..input)
 N   # push N
  ¿  # gcd(input, N)
   – # if 1, print N

Neil A.

Posted 2016-12-26T18:00:02.387

Reputation: 2 038

2

C (gcc), 54 bytes

k;f(n){for(k=0;++k/n<n;k/n*k%n-1||printf("%u ",k/n));}

This is a port of my Python answer.

Try it online!

Dennis

Posted 2016-12-26T18:00:02.387

Reputation: 196 637

1

JavaScript (Firefox 30-57), 53 bytes

n=>[for(i of Array(n*n).keys())if(i*(i=i/n|0)%n==1)i]

Port of @Dennis's amazing Python answer. 60 bytes in ES6:

n=>[...Array(n*n)].map((_,i)=>i/n|0).filter((i,j)=>i*j%n==1)

Similar idea of looking for the multiplicative inverse, also 60 bytes in ES6:

n=>[...Array(n).keys()].filter((i,_,a)=>a.some(j=>i*j%n==1))

Neil

Posted 2016-12-26T18:00:02.387

Reputation: 95 035

1

Pyth, 5 bytes

x1iLQ

Try it online!

How it works

Note that Pyth uses 0-indexing.

x1iLQ   Q = eval(input())

x1iLQQ  implicit Q at the end
  iLQQ  [gcd(Q,0), gcd(Q,1), ..., gcd(Q,Q-1)]
x1      all occurences of 1 in the above list (return their indices)

Leaky Nun

Posted 2016-12-26T18:00:02.387

Reputation: 45 011

1

Husk, 7 6 bytes

§foε⌋ḣ

-1 thanks @Leo!

Try it online!

Explanation

        -- implicit input N
§f   ḣ  -- filter the range [1..N] with
  oε⌋   --   is gcd(N,·) at most 1

ბიმო

Posted 2016-12-26T18:00:02.387

Reputation: 15 345

1

C (gcc), 99 bytes

#include<stdio.h>
g(a,b){return b>0?g(b,a%b):a;}c(n,i){for(i=1;i<n;i++)g(n,i)<2?printf("%i ",i):0;}

Try it online!

ATaco

Posted 2016-12-26T18:00:02.387

Reputation: 7 898

1

Java 8, 98 bytes

import java.util.*;n->{Set r=new HashSet();for(int i=0;++i/n<n;)r.add(i/n*i%n==1?i/n:1);return r;}

Port of @Dennis' amazing Python answer.

Explanation:

Try it here.

import java.util.*;     // Required import for Set and HashSet

n->{                    // Method with integer parameter and Set return-type
  Set r=new HashSet();  //  Result-Set
  for(int i=0;          //  Index-integer (starting at 0)
      ++i/n<n;)         //  Loop as long as `i/n` is smaller than `n`
                        //  (starting `i` at 1 by first increasing it by 1 with `++i`)
    r.add(i/n           //   If `i/n`,
          *i%n          //   multiplied by `i` modulo-`n`,
              ==1?      //   is exactly 1:
           i/n          //    Add `i/n` to the Set
          :             //   Else:
           1            //    Add 1 to the Set
  );                    //  End of loop
  return r;             //  Return the result-Set
}                       // End of method

Kevin Cruijssen

Posted 2016-12-26T18:00:02.387

Reputation: 67 575

1

Gaia, 2 bytes

S⁇

Try it online!

I seem to have outgolfed myself.

S⁇  - Full program.

 ⁇  - Filter-Keep (operates on the automatically generated range).
S   - Check if the input and the current element are coprime.

Mr. Xcoder

Posted 2016-12-26T18:00:02.387

Reputation: 39 774

1

C 177 , 150 , 135 , 102 bytes

Not very golfy but...

p,i,t,x,y,N;f(n){
int A[9]={};
for(i=0,N=n;p<n;n/=p){
for(p=2+(n&1);n%p;)p+=2;
A[i++]=p;
}
for(y=0;y++<N;){
for(i=t=0;x=A[i++];)
t|=!(y%x);
if(!t)printf("%d ",y);
}
}

EDIT: one line 150

p,i,t,x,y,N;f(n){int A[9]={};for(i=0,N=n;p<n;n/=A[i++]=p)for(p=2+(n&1);n%p;)p+=2;for(y=0;y++<N;){for(i=t=0;x=A[i++];)t|=!(y%x);printf("\0 %d"+!t,y);}}

EDIT2:

f(n){int p,t,x,i=0,y=0,N=n,A[9]={};for(;p<n;n/=A[i++]=p)for(p=2;n%p;)p++;for(;y++<N;printf("\0 %d"+!t,y))for(i=t=0;x=A[i++];)t|=y%x<1;}

Stores array of primefactors of N,
Then prints numbers < N that don't divide those.

EDIT3:
Got rid of Array, recalulating primefactors instead

f(n){int p,t,i=0,N=n;for(;i++<N;printf("\0 %d"+!t,i))for(n=N,p=t=0;p<n;n/=p,t|=i%p<1)for(p=1;n%++p;);}

Try it online!

PrincePolka

Posted 2016-12-26T18:00:02.387

Reputation: 653

I'm pretty sure you can remove the newlines in C – Post Rock Garf Hunter – 2017-11-14T20:09:13.083

95 bytes – ceilingcat – 2018-12-21T03:47:42.790

1

Funky, 59 bytes

g=(a,b)=>b?g(b,a%b):(a>1)ort[#t]=i
f=n=>fort={}n>i++g(n,i)t

This defines the function f, which generates a list of all co-primes from 1 to n.

Try it online!

ATaco

Posted 2016-12-26T18:00:02.387

Reputation: 7 898

1

Pari/GP, 28 bytes

n->[x|x<-[0..n],gcd(x,n)==1]

Try it online!

Jeppe Stig Nielsen

Posted 2016-12-26T18:00:02.387

Reputation: 602

1

SNOBOL4 (CSNOBOL4), 149 bytes

	DEFINE('G(A,B)')
	N =INPUT
I	X =X + 1
	EQ(X,N)	:S(END)
	K =G(N,X)
	OUTPUT =EQ(K,1) X :(I)
G	T =REMDR(A,B)
	A =B
	B =T
	G =EQ(B) A	:F(G)S(RETURN)
END

Try it online!

Uses the Euclidean algorithm in the function G to calculate the GCD; prints values with newlines between them.

	DEFINE('G(A,B)')		;*let the interpreter know a function G is available
	N =INPUT			;*read input
I	X =X + 1			;*increment step
	EQ(X,N)	:S(END)			;*if X==N, end
	K =G(N,X)			;*K =GCD(N,X)
	OUTPUT =EQ(K,1) X :(I)		;*if K==1, output X. goto I
G	T =REMDR(A,B)			;*function body: euclidean algorithm
	A =B
	B =T
	G =EQ(B) A	:F(G)S(RETURN)	;*if B==0, G=A and return.
END

Giuseppe

Posted 2016-12-26T18:00:02.387

Reputation: 21 077

1

J, 16 Bytes

C=:I.@(1:=]+.i.)

C for coprime.

How it works:

C=:                | Define the verb C
             i.    | Integers between 0 and n-1 inclusive
          ]+.      | GCD with n. Gets applied to each element of i.n
       1:=         | Test whether each element of the array is 1. If it is, put 1, otherwise 0
   I.              | Return the indexes of the 1s. If there are none (i.e., on input 1) returns 0.

Parenthesis and @ are just so it gets executed in the right order.

Step by step example:

    (]+.i.) 10
10 1 2 1 2 5 2 1 2 1

    (1:=]+.i.) 10
0 1 0 1 0 0 0 1 0 1

    I.@(1:=]+.i.) 10
1 3 7 9

    C 10
1 3 7 9

Bolce Bussiere

Posted 2016-12-26T18:00:02.387

Reputation: 970

1

Whispers v2, 65 bytes

> Input
> 1
>> (1]
>> L⊓1
>> L=2
>> Select∘ 4 5 3
>> Output 6

Try it online!

Uses the recently implemented Select∘ command.

How it works

The entire program is built from lines 4, 5 and 6

>> L⊓1
>> L=2
>> Select∘ 4 5 3

This is the first use of any of the three Select statements, this time using the Select∘ statement. All forms of the Select statements take n line references as arguments. The last number references the array to select from (let's say \$A\$), and the others reference the functions to iterate over that array (i.e the array of functions, \$B\$). However, they differ as follows:

  • Select∧ - Only select elements which are truthy under all functions in \$B\$:

$$R := [x \in A \: | \: f(x) \top, \forall f \in B]$$

  • Select∨ - Only select elements which are truthy under any function in \$B\$

$$R := [x \in A \: | \: f(x) \top, \exists f \in B]$$

  • Select∘ - Only select elements which, when all functions in \$B\$ are composed together, are truthy under this new function:

$$\text{Let }B := [f(x), g(x), h(x)]$$ $$R := [x \in A \: | \: h(g(f(x))) \: \top]$$

In this program, we can define \$A := [1, 2, ..., \alpha-1, \alpha]\$, where \$\alpha\$ is the input. We then define line 4 (>> L⊓1) as \$f(x) = \gcd(x, \alpha)\$ and line 5 (>> L=2) as \$g(x) := (x = 1)\$. Finally, we can define \$B = [f(x), g(x)]\$. This sets us up for the select statement as shown above.

When we encounter the Select∘ statement, we take \$R\$ (the final array) as defined by the third relationship above. To make things slightly easer, we'll define

\begin{align} h(x) & := g(f(x)) \\ & := gcd(x, \alpha) = 1 \end{align}

\$R\$ is then equal to the array where \$\forall x \in R\$, \$h(x) \: \top\$. Finally, on the last line, we output \$R\$.

Shorter version, 56 bytes

> Input
> 1
>> (1]
>> L⟂1
>> Select∘ 4 3
>> Output 5

Try it online!

This is much less interesting as it uses the co-prime builtin. In this case, any of the three select statements can be used.

caird coinheringaahing

Posted 2016-12-26T18:00:02.387

Reputation: 13 702

0

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.

Mama Fun Roll

Posted 2016-12-26T18:00:02.387

Reputation: 7 234

0

Julia 1.0, 33 bytes

(n)->[k for k=1:n if gcd(n,k)==1]

Try it online!

sirex

Posted 2016-12-26T18:00:02.387

Reputation: 101