Illiteral Prime numbers

4

1

Your challenge is to write a program (full program, not a function), that will take an integer and output all prime numbers up to (including) the given integer. Output is any readable list containing all integer primes (array, string, 1 prime per line, whatever you want) and must run to stdout or equivalent.

Simple? Here's the twist:

You may not use literals in your program. These include:

  • Literal numbers (0 through 9)
  • Literal strings (in quotes)

You may not use built in prime checks

EDIT: A prime check is a built in function that

  • Returns if a number is a prime number
  • Returns a prime number
  • Returns a list of prime numbers

You may code your own functions that do the above

Prime factorisation functions are allowed

As this is code-golf, shortest answer in bytes wins

7H3_H4CK3R

Posted 2016-05-27T08:58:45.417

Reputation: 81

Question was closed 2016-06-22T21:56:30.857

6

This is an occurence of the Do X without Y problem. Not that this question is bad, just wanted to know.

– user48538 – 2016-05-27T09:13:42.717

7What about prime-factorization builtins? – Denker – 2016-05-27T09:49:01.833

What if a language has a function that produces a predefined literal? Say function f outputs 1, can that be used instead of 1? – Luis Mendo – 2016-05-27T09:55:07.983

@LuisMendo if it is really built in and not self coded, sure – 7H3_H4CK3R – 2016-05-27T09:59:07.687

7You may not use built in prime checks Does that forbid prime factorization as well (i.e. a built-in function that computes prime factors of a number)? – Luis Mendo – 2016-05-27T10:23:08.427

Is the input on the command line or STDIN or either? – Brad Gilbert b2gills – 2016-05-27T15:53:51.543

@BradGilbertb2gills doesnt matter. either are fine. – 7H3_H4CK3R – 2016-05-27T16:19:33.507

I'm voting to close as unclear because "prime checks" is not very descriptive - are builtins that compute prime factorization, nth prime, or other prime-related functions (that are not necessarily primality testing) allowed? – Mego – 2016-05-27T23:16:57.517

4

Do you have a particular reason for disallowing functions? They're allowed by default and arbitrarily overriding the defaults is one of the things to avoid when writing challenges.

– Dennis – 2016-05-28T00:17:26.250

1Is 0 an integer that could be entered? Can a program end in an error for 0? – Tim – 2016-05-28T00:51:27.850

@Mego i hope to have clarified the definition. Should probably make a meta post on prime computing functions (what counts and what doesnt) – 7H3_H4CK3R – 2016-05-28T09:23:55.893

1It's still unclear to me - prime factorization functions return a list of prime numbers, so why are they allowed? And no meta post is necessary - you just have to be clearer. – Mego – 2016-05-28T09:25:21.610

@Mego i guess you have a point there, its hard to draw a boundary, but as i wrote above, Prime factorisation functions are allowed – 7H3_H4CK3R – 2016-05-28T09:26:57.657

5

If this were not already closed, I would vote to close it as a duplicate of http://codegolf.stackexchange.com/q/70001/194 . The accepted answer to that question meets all of the criteria of this one, and the others can be adapted. (Admittedly some would be more costly to adapt than others).

– Peter Taylor – 2016-05-28T09:59:18.480

Answers

8

05AB1E, 7 6 bytes

Six byte solution

Since prime factorisation is now allowed, this is my six byte solution:

LDÒ€gÏ

Explanation:

L       # Create the list [1, ..., input]
 D      # Duplicate this list
  Ò     # Get the prime factorisation of each number
   €g   # Get the length of each prime factorisation (length 1 = prime)
     Ï  # Keep the numbers for which is the index is equal to 1

Uses CP-1252 encoding. Try it online!.


Previous solution

Uses Wilson's theorem. Code:

LÐ<!n%Ï

Explanation:

L        # Generate the list [1, ..., input].
 Ð       # Triplicate the list.
  <      # Decrement the last one by one.
   !     # Take the factorial.
    n    # Square each.
     %   # Modulo the list by [1, ..., input].
      Ï  # Take the values for which the indices are equal to 1.

Visual explanation for input n = 9:

 Command - Stack

L        # [1, 2, 3, 4, 5, 6, 7, 8, 9]
 Ð       # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 3
  <      # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [0, 1, 2, 3, 4, 5, 6, 7, 8]
   !     # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [1, 1, 2, 6, 24, 120, 720, 5040, 40320]
    n    # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [1, 1, 4, 36, 576, 14400, 518400, 25401600, 1625702400]
     %   # [1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 1, 0, 1, 0, 1, 0, 0]

Which leaves us (using Ï):

[1, 2, 3, 4, 5, 6, 7, 8, 9], 
[0, 1, 1, 0, 1, 0, 1, 0, 0]

    2  3     5     7

Uses CP-1252 encoding. Try it online!.

Adnan

Posted 2016-05-27T08:58:45.417

Reputation: 41 965

6

Jelly, 10 9 8 7 bytes

1 byte saved thanks to Dennis.

Ṗ!²%ḊT‘

Try it online!

This is my first (working) Jelly program. I have no idea what I'm doing. :P

Also uses Wilson's theorem.

PurkkaKoodari

Posted 2016-05-27T08:58:45.417

Reputation: 16 699

4I had that same feeling with my first Jelly answer, only in my case it was non-working – Luis Mendo – 2016-05-27T14:26:29.220

6

05AB1E, 2 bytes

!f

Allowing prime factorization makes this a bit too easy...

Try it online!

How it works

!   Compute the factorial of the input.
 f  Find its prime factors.

Dennis

Posted 2016-05-27T08:58:45.417

Reputation: 196 637

And, as the legend goes, nobody ever out golfs Dennis. – noɥʇʎԀʎzɐɹƆ – 2016-06-22T18:46:07.117

5

Pyth, 11 bytes

f!%h.!tTTtS

Try it online.

Uses Wilson's theorem. Not my own idea (suggested to DenkerAffe by Leaky Nun & used already by Adnan), so I'm making it a community wiki.

PurkkaKoodari

Posted 2016-05-27T08:58:45.417

Reputation: 16 699

Meh, was planning to do that after work, already spent too much time here on this :P But whatever, well done ;) – Denker – 2016-05-27T12:14:10.053

2I don't know why, but I immediately read this code as fishsticks – Alexis Andersen – 2016-05-27T14:35:10.560

What about {P.!Q ? – drobilc – 2016-05-28T12:43:26.637

@drobilc P would be a prime builtin which are disallowed. – PurkkaKoodari – 2016-05-28T15:34:18.807

@Pietu1998 Yes, but I'm using P as a prime factorisation function, which is allowed. – drobilc – 2016-05-28T18:25:42.033

Prime factorisation is allowed: {P.! works for 4 bytes (if anyone is still interested in this challenge anymore) – Mr. Xcoder – 2017-08-04T16:32:44.610

3

JavaScript (ES6), 98 bytes

alert([...Array(-~(n=prompt())).keys()].filter(n=>n>!!n&&[...Array(n)].ev‌​ery((_,i)=>i==!!i||n%i)))

f=n=>[...Array(-~n).keys()].filter(n=>n>!!n&&[...Array(n)].every((_,i)=>i==!!i||n%i))
<input id=i oninput=o.value=f(i.value)><input id=o>

Neil

Posted 2016-05-27T08:58:45.417

Reputation: 95 035

Would it be shorter to use regex matching? – Leaky Nun – 2016-05-27T09:40:14.590

I think n=>[...(a=Array)(-~n).keys()].filter(n=>n>!!n&&[..a(n)].every((_,i)=>i==!!i||n%i)) is shorter – Bálint – 2016-05-27T10:24:10.253

@Bálint Only because you accidentally deleted one of the .s before the a. – Neil – 2016-05-27T10:29:45.423

From the description of the challenge, on the first line: "Your challenge is to write a program (full program, not a function) [...]". You currently have a function, not a full program. A full program would be (n=>[...Array(-~n).keys()].filter(n=>n>!!n&&[...Array(n)].every((_,i)=>i==!!i||n%i)))(prompt()). I will reverte the downvote once any necessary change is made. – Ismael Miguel – 2016-05-27T13:33:46.803

That is still just a function, but, I removed the downvote since the question was closed. – Ismael Miguel – 2016-05-29T18:50:29.233

@IsmaelMiguel Ah, you want me to add 3 bytes to actually invoke the function too? I can do that. – Neil – 2016-05-29T19:43:48.110

Or, you can do like this: console.log([...Array(-~(n=prompt())).keys()].filter(n=>n>!!n&&[...Array(n)].every((_,i)=>i==!!i||n%i))), which is a full program that only takes 104 bytes. – Ismael Miguel – 2016-05-29T23:29:59.753

3

Ruby, 53

$..upto(gets.to_i){|i|($....i).one?{|f|i%f<$.}&&p(i)}

This uses the $. magic variable in place of numeric literals, since it starts off as 0 and is incremented when we call gets to read from standard input. We can then define a prime number as a number that has exactly one factor less than it ($....i means the range from 1 to i excluding i) to avoid erroneously printing 0 and 1.

histocrat

Posted 2016-05-27T08:58:45.417

Reputation: 20 600

I didn't realize that Ruby copied the $. variable from Perl. – Brad Gilbert b2gills – 2016-05-27T16:10:45.097

2

Retina, 29 27 bytes

!&`(?!.$|(?<k>..+)\<k>+$).+

Try it online!

Input/output in unary.

How it works:

It matches, with overlapping (&), the substrings of the input that are not 1 ((?!.$) and are not composite numbers ((?<k>..+)\<k>+$), then output all matches linefeed-separatedly (!)

Leaky Nun

Posted 2016-05-27T08:58:45.417

Reputation: 45 011

2

Pyth, 13 bytes

fqh!Z/%LTSTZS

Try it here!

Explanation

Using the shortest (but most inefficient) way to check for primes.

fqh!Z/%LTSTZSQ    # implicit: Q = input

f           SQ    # Filter [1...Q] with T
       L ST       # Map over [1...T]
      % T         # T module the lambda var
     /     Z      # Count number of zeroes
 qh!Z             # If ^ is 2, it's a prime

Denker

Posted 2016-05-27T08:58:45.417

Reputation: 6 639

Would it be shorter to use Wilson's theorem? – Leaky Nun – 2016-05-27T09:40:36.500

Checking if a number is equal to 2 can be done with: !tt – Jakube – 2016-05-27T22:30:41.620

2

MATL, 10 bytes

:t!\~sqq~f

Try it online!

It could be shortened to 9 bytes using H (which produces predefined literal 2). But it feels like cheating:

:t!\~sH=f

Try it online!

Explanation

:     % Implicitly take input N. Generate row vector [1 2 ... N]
t!    % Duplicate and transform into column vector
\     % Modulo operation, element-wise with broadcast
~     % Logical negate. Transform zeros to 1, non-zeros to 0
s     % Sum of each column
qq    % Decrement by 1, twice. Zeros correspond to primes
~f    % Indices of zeros. Implicitly display

Luis Mendo

Posted 2016-05-27T08:58:45.417

Reputation: 87 464

1

JavaScript (ES6), 110 bytes

f=n=>{p=true;q=[];for(i=p+p;i<=n;i++){for(j=i/i;++j<i;p=i%j?p:p>p);p?q.push(i):i;p=true}alert(q)};f(+prompt())

Thanks to @LeakyNun for helping me shorten my solution.

Arjun

Posted 2016-05-27T08:58:45.417

Reputation: 4 544

i=true+true -> i=p+p – Leaky Nun – 2016-05-27T14:08:35.240

for(j=true+true;j<i;j++)i%j==false?p=false:null; -> for(j=i/i;++j<i;p=i%j?p:p<p); – Leaky Nun – 2016-05-27T14:23:34.543

p?q.push(i):null; -> p+=p?","+i:""; – Leaky Nun – 2016-05-27T14:27:20.237

for(...){} -> for(...); – Leaky Nun – 2016-05-28T01:09:10.970

for(i=p+p;i<=n;p?q.push(i):i,i++)for(p=true,j=p;++j<i;p=i%j?p:p>p); – Leaky Nun – 2016-05-28T01:15:19.207

And since I can't post any more answer now... f=n=>{for(i=true,f=i,p=[];++i<=n;f*=i)(f+i/i)%i?i:p.push(i);alert(p)};f(+prompt()) (Uses Wilson's theorem) – Leaky Nun – 2016-05-28T01:42:53.843

1

Brachylog, 6 bytes

$!$pd.

Saved a crapload of bytes thanks to @LeakyNun, who pointed out that you can use prime factorization built-ins.

Fatalize

Posted 2016-05-27T08:58:45.417

Reputation: 32 976

$!$pd should save some bytes – Leaky Nun – 2016-06-22T14:01:16.743

@LeakyNun Since the rule about prime built-ins was unclear, I chose not to use any, prime factorization included. It would save bytes though, that's for sure. – Fatalize – 2016-06-22T14:16:15.563

The question said prime factorization is allowed. – Leaky Nun – 2016-06-22T14:18:24.647

@LeakyNun Thanks. – Fatalize – 2016-06-22T14:35:35.580

1

Perl 6,  51 48  47 bytes

.say for grep {!first $_%%*,[*]^.. .sqrt},[*]^..get
.say for grep {!first $_%%*,[*]^..^$_},[*]^..get
.say for grep {!grep $_%%*,[*]^..^$_},[*]^..get

Explanation:

[*] / [*] () multiply all of the elements of an empty list, which results in 1.

$_ %% * is a WhateverCode that returns True if $_ is divisible by its only argument.

.say   # call the .say method on:
for    # every value from:
  grep # only those that match:

    {  # bare block with $_ for parameter
       # ( this block returns True when the value is prime )
      !          # negate: ( True for Nil, False for a number )

      first      # return the first value that is
        $_ %% *, # divisible by one of the following

        # 「2 .. $_.sqrt.floor」

        [*]      # 1
        ^..      # Range that ignores the first value
        .sqrt    # the square root of the value we are checking for primality
    },

    # 「2 .. get」

    [*]         # 1
    ^..         # Range that ignores the first value
    get         # read a line from $*IN

The 48 byte example tests against a Range that is from 1 up to the value to check for primality, excluding both end points.


That will run slower as the prime numbers increase, as it checks against all values up to the square root of the number it is testing. It will be more performant if you cache the primes as you go, and only test against them.
( There may be a point where the previous code will be more performant if you run out of memory, and it has to page the cache out to disk )

my @p;.say for grep {push @p,$_ if !first $_%%*,@p},([*])^..get

The normal way to write something that prints out primes would be:

.say for grep *.is-prime, 2..get

( I would probably use @*ARGS[0] instead of get so that it gets input from the command line instead of STDIN )

Brad Gilbert b2gills

Posted 2016-05-27T08:58:45.417

Reputation: 12 713

my @p;.say for grep {push @p,$_ if !first $_%%*,@p[{0..$_/2}]},([*])^..get would be even more performant – Brad Gilbert b2gills – 2016-05-27T16:43:12.403

1

J, 22 bytes

([:>:@I.>:|*:@!)@i.@x:

Also uses Wilson's theorem.

Usage

   f =: ([:>:@I.>:|*:@!)@i.@x:
   f 9
2 3 5 7
   f 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

miles

Posted 2016-05-27T08:58:45.417

Reputation: 15 654

1

Python 2, 74 bytes

lambda n:[-p for p in range(-n,n/-n)if all(p%i for i in range(-~True,-p))]

Lynn

Posted 2016-05-27T08:58:45.417

Reputation: 55 648

Is this a function? – Tim – 2016-05-28T00:41:53.743

0

Python 2, 59 58 bytes

n=input();k=p=n/n
while k<n:
 p*=k*k;k=-~k
 if p%k:print k

Test it on Ideone.

Dennis

Posted 2016-05-27T08:58:45.417

Reputation: 196 637

0

Python 2, 102 bytes

p=input()
q=p/p
print[i if min([i%l for l in range(q+q,i)]+[q])>q-q else None for i in range(q+q,p+q)]

Tim

Posted 2016-05-27T08:58:45.417

Reputation: 2 789

0

Perl 5, 37 bytes

36, plus 1 for -nE instead of -e

{/^.?$|^(..+?)\1+$/||say;s/.//;redo}

Input and output are in unary.

msh210

Posted 2016-05-27T08:58:45.417

Reputation: 3 094

If \1 is considered using a literal number, I can use \g1 instead at the expense of a byte. But it shouldn't be so considered: it's really a variable name. – msh210 – 2016-05-30T03:15:27.200

0

Mathematica, 43 bytes

Select[Range@Input[],Tr@Rest@Divisors@#==#&]

Selects from a range of integers between 1 and Input[] those, the sum of whose divisors, except the first one (in ascending order) is equal to the number itself.

LLlAMnYP

Posted 2016-05-27T08:58:45.417

Reputation: 361

0

Dyalog APL, 14 bytes

((⊢~∘.×⍨)≢↓⍳)⎕

Fully parenthesised:

(⊢ ~ ((∘.×)⍨)) (≢ ↓ ⍳)

Every triple of functions applies the right and left monadic functions separately to whatever is outside of the parenthesis, and then the two results become the arguments of the middle function, thus (f g h)A is (f A) g (h A). This repeat itself until the following tree structure:

    ┌──────┴──────┐
 ┌──┼────┐     ┌──┼──┐
┌┴┐┌┴┐┌──┴──┐ ┌┴┐┌┴┐┌┴┐
│⊢││~││∘.× ⍨│ │≢││↓││⍳│
└─┘└─┘└─────┘ └─┘└─┘└─┘

prompt for numeric input

Let's assume the user inputs 6:

tally the input (giving 1) and indices until the input (giving 1 2 3 4 5 6)

1 ↓ 1 2 3 4 5 6 drop 1 from the list (giving 2 3 4 5 6)

pass through (2 3 4 5 6) and ∘.×⍨ multiplication table:

 4  6  8 10 12
 6  9 12 15 18
 8 12 16 20 24
10 15 20 25 30
12 18 24 30 36

2 3 4 5 6 ~ 4 6 8 10 12 6 9… "without" (i.e. set difference), yielding 2 3 5

TryAPL!

Adám

Posted 2016-05-27T08:58:45.417

Reputation: 37 779

0

J, 7 bytes

~.@q:@!

~. unique @ of q: prime factors @ of ! factorial

Adám

Posted 2016-05-27T08:58:45.417

Reputation: 37 779