A prime test that's LITERALLY prime

23

2

Write a program that will test the primality of a specified number, and give the output as a Boolean value (True is prime). Your prime test can (but doesn't have to) be valid for the number 1.

Here's the catch: your program itself has to sum to a prime number. Convert every character (including spaces) to its Unicode/ASCII value (table). Then, add all those numbers together to get the sum of your program.

For example, take this not-so-great program I wrote in Python 3.3:

q=None
y=int(input())
for x in range(2,int(y**0.5)+1):
    if y%x==0:
        q=False
if not q:
    q=True
print(q)

If you convert all the characters to their corresponding Unicode/ASCII value, you get:

113 61 78 111 110 101 10 121 61 105 110 116 40 105 110 112 117 116 40 41 41 10 102 111 114 32 120 32 105 110 32 114 97 110 103 101 40 50 44 105 110 116 40 121 42 42 48 46 53 41 43 49 41 58 10 32 32 32 32 105 102 32 121 37 120 61 61 48 58 10 32 32 32 32 32 32 32 32 113 61 70 97 108 115 101 10 105 102 32 110 111 116 32 113 58 10 32 32 32 32 113 61 84 114 117 101 10 112 114 105 110 116 40 113 41 

You can then find the sum of those numbers manually or with your own program. This specific program sums to 8293, which is a prime number.

Of course, this is Code Golf, so the smaller you can make your program, the better. As pointed out by other users, this program is not very golfy.

A few rules:

Valid inputs include STDIN and prompts (no functions, it's just a way to add free extra code). Spaces are permitted, but only if they are crucial to the functionality of your program. Output must be an output, not just stored in a variable or returned (use print, STDOUT, etc.)

Flags can be used and should be counted literally, not expanded. Comments are not allowed. As for non-ASCII characters, they should be assigned to the value in their respective encoding.

Make sure to list your program's size and the sum of the program. I will test to make sure programs are valid.

Good luck!

Here is a snippet to count the sum of your program and check if it is prime:

function isPrime(number) { var start = 2; while (start <= Math.sqrt(number)) { if (number % start++ < 1) return false; } return number > 1; } var inp = document.getElementById('number'); var text = document.getElementById('input'); var out = document.getElementById('output'); function onInpChange() { var msg; var val = +inp.value; if (isNaN(val)) { msg = inp.value.toSource().slice(12, -2) + ' is not a valid number.'; } else if (isPrime(val)) { msg = val + ' is a prime number!'; } else { msg = val + ' is not a prime number.'; } out.innerText = msg; } function onTextChange() { var val = text.value; var total = new Array(val.length).fill().map(function(_, i) { return val.charCodeAt(i); }).reduce(function(a, b) { return a + b; }, 0); inp.value = '' + total; onInpChange(); } text.onkeydown = text.onkeyup = onTextChange; inp.onkeydown = inp.onkeyup = onInpChange;
body { background: #fffddb; } textarea, input, div { border: 5px solid white; -webkit-box-shadow: inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); -moz-box-shadow:  inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1); box-shadow:  inset 0 0 8px  rgba(0,0,0,0.1), 0 0 16px rgba(0,0,0,0.1);  padding: 15px; background: rgba(255,255,255,0.5); margin: 0 0 10px 0; font-family: 'Roboto Mono', monospace; font-size: 0.9em; width: 75%; }</style><meta charset="utf-8"><style>/**/
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet"><textarea id="input" tabindex="0">Insert your (UTF-8 encoded) code here
Or directly input a number below</textarea><br><input id="number" value="6296" tabindex="1"><br><div id="output">6296 is not a prime number.</div>

Noah L

Posted 2017-01-24T04:41:00.297

Reputation: 805

12In non-golfing languages, it looks like you could just take the shortest prime-deciding code, and tweak variable names until the sum is prime. – xnor – 2017-01-24T04:52:20.860

5Why the restrictions on I/O? – Jonathan Allan – 2017-01-24T04:59:25.040

@JonathanAllan To prevent excessive and useless code. For example, if function arguments were allowed, you could choose a name for your function that would perfectly match the number you wanted. – Noah L – 2017-01-24T05:01:13.763

2What's a "Unibyte value" ?!??? – aditsu quit because SE is EVIL – 2017-01-24T11:38:06.197

Is our code allowed to exit with an error? – mbomb007 – 2017-01-24T23:03:17.280

1"Flags can be used and should be counted literally, not expanded." What does this mean? If my program runs as perl -ne 'your code here', do I count the n which is the edit distance, or the -n? – Value Ink – 2017-01-24T23:19:12.787

Are built-ins allowed? – mbomb007 – 2017-01-25T01:30:32.243

@mbomb007 Provided the built-ins come with the software by default (no custom-made built ins) – Noah L – 2017-01-25T01:41:56.430

1Do the I/O restrictions still allow full programs that take an argument? – Jonathan Allan – 2017-01-25T04:34:14.160

5You talk about characters and code pages. A Unicode character has always the same code point, no matter which encoding is used to represent it. As for non-ASCII characters, they should be assigned to the value in their respective encoding. makes me think you actually want the sum of the byte values to be prime – Dennis – 2017-01-25T20:28:44.657

3Test Your code online – Titus – 2017-01-25T21:54:55.583

@Titus It looks like your script is thrown off by the sequence >0 in the input: Try it online!

– Laikoni – 2018-04-02T10:27:44.507

@Laikoni It´s not >0, it´s 0. Here is a fixed version: Verify primarity of your code.

– Titus – 2018-04-02T11:12:57.883

Is it a lowest score or a shortest code? – l4m2 – 2018-04-02T15:18:00.743

@l4m2 The tag is code-golf, so it should be shortest code. (Or equivalently, the score is the byte length.) Challenges where the score is something special are usually tagged as code-challenge. – Ørjan Johansen – 2018-04-02T17:58:28.333

Answers

22

hello, world!, 13 bytes, 1193

hello, world!

Gurupad Mamadapur

Posted 2017-01-24T04:41:00.297

Reputation: 1 791

1*perfect*. I heard of this language before, but to think it also happened to have a perfect byte sum for this challenge :D – Value Ink – 2017-01-26T19:55:53.130

7

Ruby, sum 3373, 37 bytes

require'prime'
g=gets.to_i
p g.prime?

Value Ink

Posted 2017-01-24T04:41:00.297

Reputation: 10 608

6

Microscript II, 2 bytes (sum 137)

N;

Microscript II, 4 bytes (sum 353)

N;ph

I'm actually quite surprised that both of these wound up having prime byte sums.

SuperJedi224

Posted 2017-01-24T04:41:00.297

Reputation: 11 342

4

Python 2, 50 bytes, 4201

Works for 1. Output is positive if prime, or zero if not.

p=input();print all(p%m for m in range(2,p))*~-p;p

Try it online


Python 2, 44 bytes, 3701

Doesn't work for 1. Outputs a Boolean.

p=input();print all(p%k for k in range(2,p))

Try it online

mbomb007

Posted 2017-01-24T04:41:00.297

Reputation: 21 944

4

Japt, 2 bytes, 191

Uj

U :85

j : 106

Try it online!

Oliver

Posted 2017-01-24T04:41:00.297

Reputation: 7 160

4

Pyth, 2 bytes, 127

/P

Try it online

Outputs 1 for primes, 0 for non-primes.

/ has code point 47. P has code point 80.

How it works:

/P
/PQQ    Implicit variables.
        Q = input
 PQ     Prime factorize Q.
/  Q    Count how many times Q appears. 1 if prime, 0 if not.

isaacg

Posted 2017-01-24T04:41:00.297

Reputation: 39 268

4

Haskell, 52 bytes, 4421

main=do
 k<-readLn
 print$product[1..k-1]`rem`k==k-1

Wilson theorem.

fquarp

Posted 2017-01-24T04:41:00.297

Reputation: 41

2Turned it into a full standalone program. – fquarp – 2018-04-01T21:00:47.917

The ::IO Int really shouldn't be necessary unless that's the shortest way you can get a prime sum. – Ørjan Johansen – 2018-04-02T00:11:50.387

Good call. However, we then get some code that `hashes' to an even value. Adding spaces or new-lines does nothing (even values), nor does changing the name of the variable (it appears four times, so replacing its code (say c) amounts to subtracting 4 * c and adding 4 * c', leaving the sum even. However, it can be tweaked by breaking the lines and still be shorter, which I did. – fquarp – 2018-04-02T09:23:11.290

1

47 bytes with a different primality test: Try it online! (note that there are tabs instead of spaces to get the count right).

– Laikoni – 2018-04-02T10:39:48.543

Also welcome to PPCG! – Laikoni – 2018-04-02T10:40:16.647

@Laikoni well done. I think yours will be hard to beat. – fquarp – 2018-04-02T12:40:25.567

3

JavaScript (ES6), 47 bytes, 3541

This is heavily based on ETHproductions primality-testing function, which can be found here.

alert((F=(n,x=n)=>n%--x?F(n,x):!~-x)(prompt()))

Arnauld

Posted 2017-01-24T04:41:00.297

Reputation: 111 334

3

05AB1E, 2 bytes, 173

p=

Explanation:

p  # Checks if number is prime - returns 1 if true and 0 if false. Uses implicit input.
 = # Wouldn't usually be required for this sort of program, but I added it to make the sum prime.

Try it online!

Okx

Posted 2017-01-24T04:41:00.297

Reputation: 15 025

Something something "comments are not allowed" but I guess effective no-ops work fine :D – Value Ink – 2017-01-26T19:53:56.730

2

R, 27 32 bytes, sum 2243 2609

Saved a 5 bytes thanks to @rturnbull

cat(gmp::isprime(scan(),r=43)>0)

This makes use of the gmp library's isprime function.

> sum(as.integer(charToRaw('cat(!!gmp::isprime(scan()))')))
[1] 2243
> cat(!!gmp::isprime(scan()))
1: 2243
2: 
Read 1 item
TRUE
> 

MickyT

Posted 2017-01-24T04:41:00.297

Reputation: 11 735

cat(!!gmp::isprime(scan())) is 5 bytes shorter, and sums to 2243, also prime. – rturnbull – 2017-01-26T09:52:52.617

@rturnbull thanks for that :) – MickyT – 2017-01-26T17:52:32.033

2

PHP, 38 bytes, sum 2791

Fun fact: With $h instead of $c, the sum would be 2801 (also a prime), and its binary representation 101011110001 read as decimal is also a prime number.

for($b=$c=$argv[1];$c%--$b;);echo$b<2;

takes command line argument, prints 1 or empty string. Run with -r.

Code taken from my own prime function (look at the original post if you can).

Titus

Posted 2017-01-24T04:41:00.297

Reputation: 13 814

@Artyer It´s fixed. – Titus – 2017-01-25T20:40:26.920

1

Python 2, 44 bytes, byte-sum 3109

This is xnor's 44 byte implementation with the lowest valued variable names that yield a prime byte sum.

Prints 1 if prime and 0 if not.

C=B=1
exec"B*=C*C;C+=1;"*~-input()
print B%C

Jonathan Allan

Posted 2017-01-24T04:41:00.297

Reputation: 67 804

1

Jelly 6 bytes, byte-sum 691

ƓÆḍ,ṠE

prints 1 if prime and 0 if not.

TryItOnline!

The bytes in hexadecimal are 93 0D D5 2C CD 45 (see the code page), or in decimal are 147 13 213 44 205 69 which sum to 691, which is prime.

How?

ƓÆḍ,ṠE - Main Link: no arguments
Ɠ      - read and evaluate a line from STDIN (integer expected)
 Æḍ    - proper divisor count
   ,   - paired with
    Ṡ  - sign
     E - all equal? - returns a boolean (1 or 0)
       - implicit print

The Æḍ functionality is such that primes and their negations return one while other integers do not (composites and their negations return numbers greater than one, one and minus one return zero and zero returns, oddly enough, minus one).

The functionality is such that negative integers return minus one, zero returns zero and positive integers return one.

Thus the two functions only return the same value for the primes.

Note that the 3 byte program ƓÆP which directly tests if the input from STDIN is prime is unfortunately not a prime-sum program (240).

Testing for equality using =(equals), e(exists in), or (non-vectorising equals) for 5 bytes also do not yield prime-sum programs.


Alternative (maybe not acceptable) 4 bytes, sum 571

If the I/O restrictions still allow full programs that take an argument.

Æḍ⁼Ṡ

...using the same principle as above, where is non-vectorising equality (the non-vectorising aspect has no effect since there is nothing to vectorise over anyway). The hex values are 0D D5 8C CD which are 13 213 140 205 in decimal which sum to 571, a prime.

Again note that the 2 byte program ÆP does not have a prime sum (93).

Jonathan Allan

Posted 2017-01-24T04:41:00.297

Reputation: 67 804

ƓÆPG (311) and ÆPF (163) should be fine, I think? – Lynn – 2017-01-25T19:30:25.707

As Unicode, for ƓÆḍ,ṠE, the value is 16183, which is coincidentally prime! – Artyer – 2017-01-25T20:38:47.610

@Lynn Yes, it seems the "unnecessary code restriction" (except for the space character) has been lifted, making ƓÆPG OK. I have also asked if a program taking input rather than the use of STDIN is acceptable. – Jonathan Allan – 2017-01-26T04:23:52.323

1...If both such things are OK then ÆP¥ is 3 bytes and 97. – Jonathan Allan – 2017-01-26T04:30:05.803

1

CJam, 4 bytes, byte-sum 439

qimp

Uses the built-in primality test.

Try it online!

Alternate solution, 4 bytes, sum 461

r~mp

Business Cat

Posted 2017-01-24T04:41:00.297

Reputation: 8 927

1

Perl 6, 24 22 bytes, 1949

say .is-prime
for +get

All three whitespace characters are required.
(Perl 6 doesn't care what kind of whitespace character they are, though, so I chose a newline instead of the more commonly used space for the second one...)

smls

Posted 2017-01-24T04:41:00.297

Reputation: 4 352

1

Mathematica, 21 bytes, 1997

Print@*PrimeQ@Input[]

Input[] reads a line of input (from STDIN if no front end is used, through a dialog box if the Mathematica front end is used), Print@*PrimeQ is the composition (@*) of the Print and PrimeQ functions, and @ is prefix function notation.

ngenisis

Posted 2017-01-24T04:41:00.297

Reputation: 4 600

1

Pyth, 4 bytes, 367

}QPQ

Try it here!

Gurupad Mamadapur

Posted 2017-01-24T04:41:00.297

Reputation: 1 791

1

Pip, 8 bytes, 511

0Na%,a=1

I wrote a prime checker, and the sum was prime. Convenient. Verify inputs 1-30: Try it online!

Explanation

          a is first command-line argument
    ,a    Numbers from 0 to a-1
  a%      Take a mod each of those numbers (a%0 gives nil)
0N        Count number of times 0 occurs in that list
      =1  If 0 occurs only 1 time (for a%1), then a is prime

DLosc

Posted 2017-01-24T04:41:00.297

Reputation: 21 213

1

C (gcc), 62 60 bytes, 4583

Pretty straight-forward. Outputs * if prime, otherwise it outputs a space. Does not work for 1.

-2 thanks to l4m2

p;main(i){for(scanf("%d",&p);++i<p;)p=p%i?p:0;puts("*"+!p);}

Try it online!

gastropner

Posted 2017-01-24T04:41:00.297

Reputation: 3 264

1n;main(i){for(scanf("%d",&n);++i<n;)n=n%i?n:0;puts("*"+!n);} may need to change some variable name for prime sum – l4m2 – 2018-04-02T15:15:36.957

@l4m2 Nice one! – gastropner – 2018-04-02T15:28:56.807

1

J, 18 Bytes, 1103

echo 1&p:".(1!:1)1

Not far from optimal, the least I could golf a full program primality test to was 17 Bytes: echo(p:[:".1!:1)1, which unfortunately sums to 1133 = 11*103.

Unfortunately I can't figure out how to get keyboard input working on TIO, so no link yet.

Explanation:

echo 1&p:".(1!:1)1  | Full program
           (1!:1)1  | Read a line of input from keyboard
         ".         | Evaluate (converts string to int)
     1&p:           | 1 for prime, 0 for composite
echo                | Print result. The space is required, as 'echo1' would be interpreted as a variable

Validating the program:

   1 p:+/u:inv'echo 1&p:".(1!:1)1'  NB. Convert to ints, sum, and test primality
1

Bolce Bussiere

Posted 2017-01-24T04:41:00.297

Reputation: 970

1

Pari/GP, 23 bytes, 2111

print(2>=numdiv(input))

Try it online!

alephalpha

Posted 2017-01-24T04:41:00.297

Reputation: 23 988

This challenge does not seem to allow functions. – Ørjan Johansen – 2018-04-01T17:36:33.053

1

AWK, 36 bytes, byte-sum 2239

{for(a=1;$0%++a&&a<$0;);$0=(a==$0)}1

Try it online!

Outputs 0 if not prime and 1 for prime. Definitely not the most efficient code, since it checks every integer greater than 1 to see if it divides the input.

Robert Benson

Posted 2017-01-24T04:41:00.297

Reputation: 1 339

1

Excel (57 bytes, code sum 3547)

=XOR(0<PRODUCT(MOD(A1,ROW(OFFSET(D2,0,,SQRT(A1))))),3>A1)

Excel doesn't really have an "input" as such, but this formula expects the number to be tested to be in A1 and outputs to whatever cell you drop it in. It's an array formula, so press Ctrl-Shift-Enter to enter it, rather than Enter.

Sophia Lechner

Posted 2017-01-24T04:41:00.297

Reputation: 1 200

1

Java 8, 114 bytes, Prime 10037

interface M{static void main(String[]a){long n=new Long(a[0]),x=2;for(;x<n;n=n%x++<1?0:n);System.out.print(n>1);}}

Try it online.

Explanation:

interface M{                     // Class
  static void main(String[]a){   //  Mandatory main-method
    long n=new Long(a[0]),       //   The first argument as number
    x=2;for(;x<n;n=n%x++<1?0:n); //   Check if `n` is a prime
    System.out.print(n>1);}}     //   Print whether `n` was a prime
                                 //    (if `n` is still the same: it's a prime;
                                 //     if `n` is now 0 or 1: it's not a prime)

I've used x instead of i to make the unicode sum a prime. Verify the unicode sum here.

Kevin Cruijssen

Posted 2017-01-24T04:41:00.297

Reputation: 67 575

1

Jelly, 4 bytes, Σ = 239

ÆPa1

Try it online!

Proof: Try it online! (take the 1-based indices of the program's chars of Jelly's code page, decrement to make them 0-based, sum and then check if the result is prime).

Erik the Outgolfer

Posted 2017-01-24T04:41:00.297

Reputation: 38 134

0

SmileBASIC, 42 bytes, 2687

INPUT N:FOR D=2TO N/2P=P+!(N MOD D)NEXT?!P

Outputs 1 (true) if the number is prime, otherwise 0 (false).

The variable names were not just chosen to make the program prime. N is the number to test, D is the divisor, and P keeps track of whether N is prime.

12Me21

Posted 2017-01-24T04:41:00.297

Reputation: 6 110

0

Wonder, 7 bytes, 537

pr rl e

There probably is a better way...

Mama Fun Roll

Posted 2017-01-24T04:41:00.297

Reputation: 7 234

0

Rust, 190 bytes, 15013 score

fn main(){let A=&mut"".into();std::io::stdin().read_line(A);let(B,mut C)=(A.trim().parse::<u64>().unwrap(),true);for H in 2..((B as f64).sqrt()+1.0) as u64{if B%H==0{C=false}}print!("{}",C)}

Ungolfed

fn main() {
    let input = &mut "".into();
    std::io::stdin().read_line(input);
    let (number, mut prime) = (input.trim().parse::<u64>().unwrap(), true);

    for x in 2..((number as f64).sqrt() + 1.0) as u64 {
        if number % x == 0 {
            prime = false;
        }
    }

    print!("{}", prime);
}

Does not work for 1

dragonite44

Posted 2017-01-24T04:41:00.297

Reputation: 91

0

Weijun Zhou

Posted 2017-01-24T04:41:00.297

Reputation: 3 396

|pQ works for a score of 317. If swapping truthy/falsy is allowed, |p! works as well for 269. – Khuldraeseth na'Barya – 2018-04-02T19:02:11.617

Thank you. I don't think the challenge require that the score be minimized so I didn't tweak that part. – Weijun Zhou – 2018-04-02T19:12:49.313

0

Whispers v2, 33 bytes

>>> ⊤ℙ∘ℕ
> Input
>> 1∘2

Try it online!

  1. Score: 44381
  2. Only 6 bytes/2 characters added to make it valid!
  3. 1 is not prime

How it works

This is shown in the order it is executed in:

		; Line 3:
>>  ∘		; Compose...
   1            ; Line 1 with
     2          ; The result of line 2

		; Line 2:
> Input		; Retrieve a line of input

		; Line 1:
>>> ⊤		; The input is...
     ℙ		; Prime
      ∘		; And it is...
       ℕ	; Natural

caird coinheringaahing

Posted 2017-01-24T04:41:00.297

Reputation: 13 702

0

JavaScript (Node.js), 33 bytes (sum 2237)

p=(n,i=1)=>++i*i>n||n%i&&p(n,i,1)

Try it online!

DanielIndie

Posted 2017-01-24T04:41:00.297

Reputation: 1 220

This challenge does not allow function solutions. – Ørjan Johansen – 2018-04-03T00:54:59.127

0

TI-Basic, 27 bytes, byte-sum 2843

Prompt F
3
For(A,2,sqrt(F
If not(remainder(F,A
0
End
Disp Ans

Prints 3 for prime and 0 for composite. Does not work for 1 (prints 3).

TI-Basic is a tokenized lanugage. remainder( is a two-byte token; all others are one-byte tokens.

Explanation:

Prompt F             # 0xdd, 0x46, 0x3f # Store input in F
3                    # 0x33, 0x3f       # Store 3 in Ans
For(A,2,sqrt(F       # 0xd3, 0x41, 0x2b, 0x32, 0x2b, 0xbc, 0x46, 0x3f
                        # For each integer A from 2 to sqrt(F)
If not(remainder(F,A # 0xce, 0xb8, (0xef, 0x32), 0x46, 0x2b, 0x41, 0x3f
0                    # 0x30, 0x3f
                        # If F is divisible by A, store 0 in Ans
End                  # 0xd4, 0x3f # end For loop
Disp Ans             # 0xde, 0x72 (no newline) # Print Ans

Sum testing with Python:

>>> sum(eval(i) for i in ['0xdd', '0x46', '0x3f', '0x33', '0x3f', '0xd3', '0x41', '0x2b', '0x32', '0x2b', '0xbc', '0x46', '0x3f', '0xce', '0xb8', '0xef', '0x32', '0x46', '0x2b', '0x41', '0x3f', '0x30', '0x3f', '0xd4', '0x3f', '0xde', '0x72'])
2843

pizzapants184

Posted 2017-01-24T04:41:00.297

Reputation: 3 174