107
\$\begingroup\$

Despite your protest, you have been put to work by your boss on a program that takes a single unsigned integer as input and prints the string "prime" if that integer is prime and "not prime" if it isn't. You may choose which language you do this in, as long as the resulting program is short; your boss very much appreciates a low character count. (He will actually manually count the characters after he prints out the source code.)

So you better get to it, the lowest character count wins.

The fun part

This is just between you and me, but your program should also be valid in another language. In this language though, it should print the string "If the boss finds this, I quit.". Make sure that your boss does not figure out there is a hidden insult when reading the code over and over as he keeps forgetting if he'd counted to 17 or 18 so far. For that reason you may not use any of the words in "the boss finds this quit" in part of the code nor can you use and anagrams of those 5 words.

Bonus challenge which I have created a bounty for

Write a program that actually looks like it just solves the first question to the untrained eye and doesn't seem to contain unnecessary characters. This includes comments and segments of code that obviously don't contribute anything. Ideally, a layman would believe that your program is actually as short as it can be without being unmanagable. A helpful comment here and there is okay though.

The rules for the bonus challenge are a bit looser, instead of being judged on easily measurable criteria, your program will be judged more on how it comes accross to me (and the voters of course)

I will be the final judge of which entry comes closest to deserving this bounty.

Edit:

After a few minutes of your boss counting, he had one of your colleages write a character counting program for him. So even characters that aren't visible count towards your character count.

\$\endgroup\$
13
  • 40
    \$\begingroup\$ Well, Whitespace people will have an easy time here. \$\endgroup\$
    – Ingo Bürk
    Aug 26, 2014 at 18:25
  • 10
    \$\begingroup\$ Unfortunately, the shortest possible Whitespace program which prints that message is 372 characters. \$\endgroup\$ Aug 26, 2014 at 19:02
  • 40
    \$\begingroup\$ But the boss will print it out and count the characters. Trailing whitespace won't count. \$\endgroup\$
    – Joshua
    Aug 26, 2014 at 19:50
  • 6
    \$\begingroup\$ The bounty challenge sounds interesting but will no doubt be won very trivially by a "well documented and indented" program in an arbitrary language (with the hidden one being whitespace). \$\endgroup\$ Aug 26, 2014 at 20:31
  • 5
    \$\begingroup\$ So far, all of the entries are obviously not serious programs (random gibberish, etc.). It would be really interesting if someone made a polyglot (that doesn't include Whitespace, of course) that actually looked reasonable at first glance (even if it was really, really long). \$\endgroup\$
    – Doorknob
    Aug 26, 2014 at 21:36

14 Answers 14

80
\$\begingroup\$

Python 2 / Python 3 - 128

n=int(input())
s="Isf  tthhies ,b oIs sq ufiitn.d"
print(["not "*any([n%a<1for a in range(2,n)])+"prime",s[::2]+s[1::2]][1/2>0])

Identifies prime numbers with Python 2, get's you into trouble with Python 3.


Bonus

__help__ = """In the forloop I'm setting the values i to n.
To be a "notPrimes", it's n % i == 0 if: 1 < i, i < n. (We
do tests i<1/2 i==1, too). Then, prints resulting, prime text.
In case i==n: quit. Just if it aborts: try."""

# read integer from command line
n=int(input())

try:

    # primes = True
    notPrimes = False

    # try each i to n
    for i in range(n):

        # ignore 0 or 1
        if i < 1 / 2 or i == 1:
            continue

        # test divisibility
        if n % i == 0:
            notPrimes = True

    # print result
    if notPrimes:
        print("not prime")
    else:
        print("prime")

except:

    # if program aborts: print help and error code
    print(__help__ [::7])

Try it with Python 2 or Python 3! (In contrast to the golf version above the roles changed: Python 3 is the prime number identifier. Python 2 contains the Easter egg.)

Please, excuse my bad English in the help text! ;)

And I do use the word "quit". But somehow I need to describe when my program terminates. ;)

\$\endgroup\$
9
  • \$\begingroup\$ exit? stop? abort? \$\endgroup\$ Aug 28, 2014 at 21:19
  • \$\begingroup\$ @MooingDuck: You mean I could use one of these words? No, then it would not work. ;) \$\endgroup\$
    – Falko
    Aug 28, 2014 at 21:21
  • \$\begingroup\$ Is this the "/ problem"? (integer division vs. floating point division) \$\endgroup\$
    – hlt
    Aug 28, 2014 at 21:22
  • 2
    \$\begingroup\$ The second one blew my mind - until I looked a bit closer. It seems that I too have fallen into the habit of reading comments rather than code. \$\endgroup\$
    – primo
    Aug 30, 2014 at 10:54
  • 3
    \$\begingroup\$ The second one is really nice! Kudos! \$\endgroup\$
    – rubik
    Aug 30, 2014 at 13:40
68
+100
\$\begingroup\$

Bonus submission (C / C++11)

Primality testing using the usual naive method is so mainstream. That's why I have invented a brand-new randomized naive method! This test is as follows:

  1. Choose any integer d at random. It must not be smaller than 2 and larger than a bit more than sqrt(n).
  2. If d is a divisor of n, output not prime.
  3. If we made this test 20sqrt(n) times, output prime, else repeat.

If the number is composite, there is only very little probability (about 10-9) that it doesn't work. Of course, I don't believe the C/C++ pseudorandom number generator is powerful enough. That's why I use my own 256-bit LFSR generator!

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* A 256-bit linear feedback shift register generating pseudorandom
 * numbers (its period is 2^256 - 1).
 */
struct LFSRGenerator {
    unsigned seed[8];
};

void lfsr_init_generator(struct LFSRGenerator *gen){
    gen->seed[0] = 0xE840CC92; gen->seed[1] = 0xC440CAD0;
    gen->seed[2] = 0x40E6E6DE; gen->seed[3] = 0xC8DCD2CC;
    gen->seed[4] = 0xD0E840E6; gen->seed[5] = 0x4058E6D2;
    gen->seed[6] = 0xEAE24092; gen->seed[7] = 0x145CE8D2;
}
void lfsr_proceed(struct LFSRGenerator *gen){
    // LFSR taps are x^256, x^254, x^251 and x^246
    unsigned new_bit =
        ((gen->seed[7]>>0)^(gen->seed[7]>>2)^
         (gen->seed[7]>>5)^(gen->seed[7]>>10)) & 1;

    // shift seed right
    gen->seed[7] >>= 1;
    int cell;
    for(cell = 6; cell >= 0; cell--){
        gen->seed[cell+1] |= ((gen->seed[cell]&1)<<31);
        gen->seed[cell] >>= 1;
    }
    gen->seed[0] |= (new_bit<<31);  // put new bit
}
void lfsr_error(struct LFSRGenerator *gen){
    fprintf(stderr, "Error! Developer info:\n");

    int cell;
    for(cell = 0; cell < 8; cell++){
        unsigned val = gen->seed[cell];
        putc((char)(val&0xFF), stderr); val >>= 8;
        putc((char)(val&0xFF), stderr); val >>= 8;
        putc((char)(val&0xFF), stderr); val >>= 8;
        putc((char)(val&0xFF), stderr);
    }
    putc('\n', stderr);
    exit(1);
}
int lfsr_get_num(struct LFSRGenerator *gen, int min_val, int max_val){
    lfsr_proceed(gen);
    int mod_num = max_val-min_val+1;   // = number of possible results
    if(mod_num <= 0)
        lfsr_error(gen);

    // take 6 first cells and compute them mod 'modNum'
    unsigned long long result = 0;
    int cell;
    for(cell = 5; cell >= 0; cell--){
        result = ((result << 32) | gen->seed[cell]) % mod_num;
    }
    return (int)result + min_val;
}

/**********************************************************************/



void end_not_prime(){
    printf("not prime\n");
    exit(0);
}
void end_prime(){
    printf("prime\n");
    exit(0);
}



int main(){ 
    int number;
    struct LFSRGenerator gen;
    lfsr_init_generator(&gen);


    printf("Provide a number to check its primality: ");
    scanf("%d", &number);

    if(number <= 1){
        end_not_prime();
    }
    if(number == 2){
        end_prime();
    }

    // just to make sure:
    //  * make 20*sqrt(n) tests
    //  * generate random divisors from 2 to 111111/100000 * sqrt(n)
    //      (in case max range doesn't include sqrt(n)
    auto num_checks = (int)floor(sqrt(number)*20);
    auto max_range = sqrt(number);
    max_range /= 100000;
    max_range *= 111111;
    max_range = floor(max_range+0.5);

    while(num_checks--){
        int rnd_div = lfsr_get_num(&gen, 2, max_range);
        if(number % rnd_div == 0){
            end_not_prime();
        }
    }
    end_prime();
}

C++11 works correctly. However, C compiler seems to be outputting a faulty program for n > 2...

Note: remember that C needs -lm option (link math library) to compile successfully.

Look at max_range variable. C++11 keyword auto resolves to a "matching type" - in this case double. However, in C it's defined as a variable modifier (as static is) - it doesn't define the type. Thus max_range type is a default C type, that is int. When we "try" to multiply this variable by 1.11111, in C it gets "unintenionally" zeroed during division by 100000. We get an incorrect interval of random numbers to be generated and LFSR after proceeding its internal state generates an error, outputting the binary dump of the seed. That's "accidentally" The message If the boss finds this, I quit.\n

If you find the following faulty output:

Error! Developer info:
If the boss finds this, I quit.

incorrect, just remove the appropriate fprintf line.

\$\endgroup\$
6
  • 4
    \$\begingroup\$ It looks pretty convincing. Care to explain a little, so I don't have to dig out my compiler? :) \$\endgroup\$
    – CompuChip
    Aug 29, 2014 at 20:48
  • \$\begingroup\$ OK, I added it. \$\endgroup\$
    – mnbvmar
    Aug 29, 2014 at 21:13
  • \$\begingroup\$ This is amazing! \$\endgroup\$
    – Ingo Bürk
    Aug 30, 2014 at 9:34
  • \$\begingroup\$ Very nice! Best answer so far, in my opinion. \$\endgroup\$
    – CompuChip
    Aug 30, 2014 at 10:59
  • \$\begingroup\$ Really impressive! \$\endgroup\$
    – Ven
    Sep 8, 2014 at 15:04
48
\$\begingroup\$

Mathematica/Brainfuck, 260

If[PrimeQ[Input[]],"prime","not prime"](*++++++++++[>+++>++++>+++++++>++++++++++>+++++++++++<<<<<-]>>>+++.>++.<<<++.>>>>++++++.<++.---.<<<.>>>---.>-----.++++..<<<<.>>>++++.+++.>-----.<-----.>+++++.<<<<.>>>>+.<++++.+.>-.<<<++++.<.>>.<<.>>>>--.++++.<.>-.<<<++.*)
\$\endgroup\$
2
  • 97
    \$\begingroup\$ Olson! This code is several times longer than it needs to be! What are all these unnecesary pluses and greater than signs for? You're fired! No, sir, I think you'll find I quit. \$\endgroup\$ Aug 26, 2014 at 18:53
  • 13
    \$\begingroup\$ @steveverrill That's one way of quiting your job I suppose. \$\endgroup\$
    – overactor
    Aug 26, 2014 at 18:54
43
\$\begingroup\$

Golfscript / Javascript (126 125 129 130 132 134 205 207)

Try Golfscript here and Javascript here.

1.//"Jg!uif!cptt!gjoet!uijt-!J!rvju/"{(}%'
alert((/^1?$|^(11+?)\1+$/.test(Array(+prompt()+1).join(1))?"not ":"")+"prime");';#'

I'd say it's shockingly close to those Mathematica solutions which, afterall, have a built-in check for prime numbers.

Edit: Thanks to Peter for saving another two six bytes!

Here's some details:

  • The first 1. is needed because the following // is a comment in Javascript, but performs division twice in Golfscript. This will error out if nothing is on the stack, so we need to give it two numbers. Incidentally, 1. is a perfectly valid syntax in Javascript and will just be ignored.
  • "…"{(}% takes the string, decrements their character code values by one and pushes it as a string. This results in the string we need to print.
  • ' starts a string in Golfscript which by default extends over several lines, causing the Javascript below to only be put into the string.
  • Next is the Javascript code, which uses a somewhat well-known approach to detect prime numbers through regular expressions.
  • ';#' closes the multi-line string in Golfscript, discards it and then ignores the rest of the line. In Javascript, this is simply a string literal which will be ignored.
\$\endgroup\$
8
  • 1
    \$\begingroup\$ In GS 1+ is ). And 1 1 is 1., which I suspect the JS would be as happy with as 1 \$\endgroup\$ Aug 26, 2014 at 20:01
  • \$\begingroup\$ @PeterTaylor Awesome, thanks! I've incorporated it. \$\endgroup\$
    – Ingo Bürk
    Aug 26, 2014 at 20:05
  • 1
    \$\begingroup\$ Also, if you map something over a string you get a string, so {)}/]""+ could just be {)}%. \$\endgroup\$ Aug 26, 2014 at 21:05
  • \$\begingroup\$ @PeterTaylor You're the man! :) \$\endgroup\$
    – Ingo Bürk
    Aug 27, 2014 at 5:01
  • 1
    \$\begingroup\$ @overactor Ugh, same mistake here. Shame on me. I'll have to fix it later tonight, though. \$\endgroup\$
    – Ingo Bürk
    Aug 27, 2014 at 12:27
37
\$\begingroup\$

CJam (GolfScript), 60 59 bytes

"Jg!uif!cptt!gjoet!uijt-!J!rvju/"{(}%S#];"not prime"limp4*>

Thanks to @mnbvmar for golfing off 1 byte!

How it works (CJam)

"Jg!uif!cptt!gjoet!uijt-!J!rvju/"  " Push that string.                                    ";
{(}%                               " Subtract 1 from each character code.                 ";
S#                                 " Find the index of the first space.                   ";
];                                 " Wrap the entire stack in an array and discard it.    ";
"not prime"                        " Push that string.                                    ";
li                                 " Read an integer from STDIN.                          ";
mp4*                               " Push 4 if it's prime and 0 if it isn't.              ";
>                                  " Remove that many chars from the start of the string. ";

Try it online!

How it works (GolfScript)

"Jg!uif!cptt!gjoet!uijt-!J!rvju/"  # Push that string.
{(}%                               # Subtract 1 from each character code.
S#];"not prime"limp4*>             # Noop followed by a comment.

Try it online!

\$\endgroup\$
2
  • 7
    \$\begingroup\$ +1: The boss is gonna love how short this is. And he definitely won't see the hidden string. He might also have trouble seeing the prime check, though. :) \$\endgroup\$
    – Ingo Bürk
    Aug 30, 2014 at 17:34
  • 6
    \$\begingroup\$ Let's hope he believes the hidden string is the prime check. \$\endgroup\$
    – Dennis
    Aug 30, 2014 at 17:37
23
\$\begingroup\$

CJam/Ruby, 132 95 91 87

0_0#;;limp4*"not prime">"
'Li#wkh#ervv#ilqgv#wklv/#L#txlw1'.bytes{|b|print (b-3).chr}#";

My previous solution was significantly over-engineered; this one was heavily inspired by Martin Büttner's solution, including his realization that the #bytes method can apparently take a block.

How does it work?

Ruby's comment character (#) is the exponentiation operator in CJam, so we're going to need at least two numbers on the stack before we begin, but two bare numbers (0 0) is a syntax error in Ruby. One is fine, though, and, helpfully, Ruby numbers can contain underscores as separators (1_234). _ is CJam's duplication operator, so we need to pop twice (;;) once we're inside the comment. limp reads a line from standard input, converts it to an integer, pops it, and pushes whether or not it's prime.

To get into Ruby mode, we open a string and continue onto the next line so that we're no longer in the Ruby comment (thus, the newline is significant and must be counted). Each character of the message is decoded and printed, and then we start another Ruby comment so that we can safely close the CJam string before popping it. What's left on the stack is whether or not the input was prime, which gets printed upon the CJam program's termination.

CJam/Whitespace, 353 (25 meaningful when printed) characters

Given the underhanded nature of the challenge, and the fact that the boss will be printing our programs in order to count the characters, I took up the suggestion of doing a solution involving Whitespace.

Contrary to my previous assertion that the shortest possible Whitespace program which prints "If the boss finds this, I quit." would be 372 characters, this one does it in 330. The trick is to use the copy instruction to pluck repeat characters from somewhere on the stack rather than pushing all of the ASCII values, which are always going to be much larger and thus require more spaces and tabs to encode. Here's a pseudo-assembly representation of the program for the curious:

push 0
push . push t push i push u push q
push 32 push I
copy 1 push , push s copy 7 push h copy 10
copy 5 copy 4 push d push n copy 6 push f
copy 5 copy 5 dup push o push b
copy 4 push e copy 14 copy 14
copy 3 copy 10 copy 23

0: dup jz 1 ochr jump 0
1: exit
\$\endgroup\$
11
  • \$\begingroup\$ It's deprecated but it works: ruby-doc.org/core-2.1.2/String.html#method-i-bytes \$\endgroup\$ Aug 26, 2014 at 19:56
  • \$\begingroup\$ It works for #chars and #lines as well, which I'll have to keep in mind for future challenges. \$\endgroup\$ Aug 26, 2014 at 19:58
  • \$\begingroup\$ I thought I tried with chars and it didn't work for some reason. \$\endgroup\$ Aug 26, 2014 at 19:59
  • \$\begingroup\$ You can use a variable such as L instead of "", and I don't think you need the + and the \ \$\endgroup\$ Aug 27, 2014 at 7:09
  • 1
    \$\begingroup\$ In fact, you can use limp4*"not prime"> to make it even shorter \$\endgroup\$ Aug 27, 2014 at 7:12
21
\$\begingroup\$

Bonus Prize Submission (Perl / B?f?n?e-?3)

Edit: I originally forgot to actually print the sentence and then noticed it would print it in reverse order. I noticed this after being done. I was about ready to kill a kitten, but I fixed it now.


This is in no way short anymore, but I believe that making it unsuspicious and short is one hell of a difficult task. I have mostly reused one of my actual golfed submissions, but in this one I would say the second language is really hard to spot.

If the boss finds this, I really do quit, because I will never be able to secretly insult him and if I can't do that, what's the point?

# ^ Prime Checker ([>:#,_@| Golf Inc. Ltd. | @_,#:<])
# ^ Ingo Bürk, (C) 2014
################################################################################################
# Input should be a "reasonably"
# small integer, or I can't guarantee
# that the check is fast at all.
#
# More Details:   - the numbers 0 and 1 are
#                   handled as not prime,
#                   even if some people disagree
#
#                 - because my employer prefers shortness                 
#                   over well-tested, modular and
#                   somewhat pretty code, the used method is
#                   somewhat questionable

#                 - first of all, the input is converted
#                   into a string of 1s such that the
#                   number of 1s equals the input;
#                   directly after that, a regexp is applied
#                   such that it checks if the input is prime

#                 - the regexp is not really my work, so I
#                   have to give attribution to its author
#                   if I want to use it here; I got it on
#                   stackoverflow:
#                   "http://stackoverflow.com/questions/3296050/how-does-this-regex-find-primes"

# <=> <--- a riddle^^
    use v5.10;

# Definition of prime number:
#############################
# "A prime is a positive integer with exactly two unique divisors."
# ,
#
# I should mention that input is given via stdin.
#
# quality documentation like this is why I get paid so much.
# use this script at your own risk.
# it has been known that checking primes like this can crash interpreters.
# this never happened to me, though.
# .
# "Less is more" -- Robert Browning (1812-1889) [Riddle Solution]

    print"not "if(1x shift)=~/^1?$|^(11+?)\1+$/;say"prime"

Bending and Breaking of the Rules:

  • I am using the word "the" in there, but it's not the "the" that gets printed. It might be technically invalid, I'll let the OP decide if the rules have to be this strict for the bonus challenge. If so, then so be it.
  • The rules state I cannot use certain words, but we read from left to right, so I assume having the words written out vertically is valid.
  • I have no idea how I still got this job, seeing the terrible things I write in comments. I mean: riddles, really?
\$\endgroup\$
9
  • 4
    \$\begingroup\$ Yay, another worthy competitor for the bonus bounty! :) \$\endgroup\$
    – Falko
    Aug 28, 2014 at 19:59
  • \$\begingroup\$ I see no problem in allowing this for the bonus question. I'd like to see some more explanation about how the Befunge program works by the way. \$\endgroup\$
    – overactor
    Aug 28, 2014 at 20:09
  • \$\begingroup\$ @overactor Thanks. I can add some explanations tomorrow, but stepping through the code e.g. here will show you how it works, too. \$\endgroup\$
    – Ingo Bürk
    Aug 28, 2014 at 20:15
  • \$\begingroup\$ @overactor It seems that the code follow certain 'arrows' (^ = move up). Certain letters of comments are placed on a stack, which is printed out at the end, printing If the boss finds this, I quit. See the example via the URL in Ingo's reaction: "!dlrow olleH">:#,_@ \$\endgroup\$
    – BlueCacti
    Aug 31, 2014 at 14:19
  • \$\begingroup\$ The boss might complain about too much documentation. It also contains some suspicious characters. \$\endgroup\$
    – tbodt
    Aug 31, 2014 at 23:42
19
\$\begingroup\$

Mathematica/Ruby, 115 106 bytes

The Mathematica part was slightly inspired by Peter Olson's submission, but the polyglotting with Ruby is a bit more elaborate here.

#If[PrimeQ@Input[],"","not "]<>"prime"&@1(*
"Jg!uif!cptt!gjoet!uijt-!J!rvju/".bytes{|c|print (c-1).chr}#*)

Ruby works, because the two # comment out everything that's Mathematica. The reason why Mathematica works is a bit more interesting. The code I want to execute is:

If[PrimeQ@Input[],"","not "]<>"prime"

But that's not valid Ruby, so I need to add a # somewhere. # is Mathematica's parameter for anonymous functions. So I put # at the front, which multiplies the argument with the result of the If. Yes, it will multiply that with a string, whatever that means. Then I turn this into an anonymous function with & and call it immediately with argument 1. Well, Mathematica is clever enough to know that multiplication by 1 is always the identity and only outputs the string. Afterwards, the Ruby code is simply put in a block comment.

\$\endgroup\$
18
\$\begingroup\$

C (Bonus Submission)

The C version is a prime checker, input array at the top. Try to guess what language yields If the boss finds this, I quit. (It's not Whitespace).

// input numbers
unsigned z[] = {4};
// number of inputs
int n = 1;

int bad(unsigned);
int good(unsigned);
// [ ... ] is used to group code into blocks to make the code easier to understand
main(c){
    if(c != 1){
        // someone needs help running this program!
        // goto the end where help text is displayed!
        // remember: gotos are not evil
        goto helpme;
    }
    int i;
    // looping down is faster than using ++
    for(i = n; i--;){
        // first we check if input is divisible by two
        // checking out of loop because `>>` is faster
        //  than `/`

        // must be either greater (not divisible by 2) or equal (divisible by 2)
        unsigned y = z[i];
        if(y > (y>>1)*2){
            // is not divisible by 2
            // we must check every other number now to ensure primality
            unsigned j;
            for(j = 3; j < z[i]; ){
                // check if number is divisible by j

                // make another copy of z[i]:
                unsigned k = z[i];

                // compilers are stupid-they have a tendency 
                //  to generate really slow code for division
                //  outside of a while loop conditional
                // therefore we do division by repeated subtraction
                // [
                    // repeated subtraction-subtract until k is less than j
                    while(k / j){
                        k -= j;
                    }
                    // if k is zero-k is divisible by j and is not a prime
                    if(!k){
                        break;
                    }
                    // bring k back down to zero-there could be
                    // memory issues if we don't-very bad
                    // afterwards continue the loop
                    while(--k > 0);
                    // increment j to continue checking
                    //  we undo if we overflowed
                    //   so we don't enter an infinite loop
                    j += 1;
                    if(j < 1){ // overflow check
                        j = 4294967295u; // max unsigned int size
                    }
                // ]
            }
            // if j >= y then y must be a prime.
            // but if j < y then j < z[i] and j must be a factor
            // j - y == 0 is used to test this-if true y is a prime
            // [
                if(j - y == 0){
                    // yay - a prime!
                    // subtraction necessary as good() and bad()
                    //  shift the value printed by 1 (who knows why)
                    good(y-1);
                }else{
                    // not a prime - oh no!
                    // output this number as not a prime
                    bad(y-1);
                }
                // we are done >+–__-+<   x_x finally! >_<
            // ]
            // >.< nearly done
            // cleanup: if y or j < 0 do -- until they are 0-
            //  avoiding memory issues is vital
            while(--y); while(--j);
        }else{
            // is divisible by 2
            // determine if this is a prime: only a prime if is 2
            // also must be non-zero
            // [
                if(!y-- || y > 1){
                    // uh oh: not a prime
                    // output
                    bad(y);
                    // undo changes to the number
                    ++y; 
                }else{
                    // prime
                    // output
                    good(y);
                    // undo changes to the number
                    y += 1;
                }
                // done here <__≥ coding is exhausting
            // ]
            // clean up! clean up! everybody everywhere!
            while(y)
                // use ++ because its faster here
                // seriously: we profiled it
                ++y;
        }
    }
    return 0;
    helpme:
    // ++-++-++-++-++-++-++-++-++-++-++-++
    // +    the dreaded HELP section     +
    // ++-++-++-++-++-++-++-++-++-++-++-++
        printf("This program checks the primality"
               " of hard coded constants\n"
               "Do not run with any arguments.\n"
               "\n");
        printf("Please press any character to see more information >");
        getchar();
        printf("This is version 1 of the primality checker.\n"
               "If your version is >=1 it is new enough to work\n");
    return 0;
}

// this prints the number x+1
//  (used because profile tests have shown it to be
//   marginally faster)
print_number(unsigned x){
    x += 1;
    // scanf is way to slow.
    // itoa is nonstandard - unacceptable for an important program 
    //   such as this primality checker!
    // we are using a loop here - recursion is dangerous and should
    //   be avoided at all costs! 
    // recursion is also absurdly slow - see recursive fib() for 
    //   an example.
    int i;
    // start from the highest place then move down all the way to the ones place
    for(i = 4000000000u / (1 << 2); i; i /= 10){
        int k = x / i % 10;
        // arrays are best avoided.
        // switches make the code convoluted
        //   so we use if chains
        if(k >= 9){
            putchar('9');
        }else if(k >= 8){
            putchar('8');
        }else if(!(--k - 6)){ // after a single round of profiling 
                              // it was determined that these 
                              // particular checks were optimal.
            putchar('7');
        }else if(4 <= --k - 0){ // a check with the -0 was shown to 
                                // be marginally faster on one test
                                // than without the -0.
            putchar('6'); 
        }else if((++k + 1) / (4 + 1)){// it's optimal! really..
            putchar('5');
        }else if(3 <= k){ // constant first to avoid problems with missing `=`s.
            putchar('4');
        }else if(k > 0 && k / 2 > 0){
            putchar('3');
        }else if(++k + 1 == 1+2){ // this secret optimization is a company secret.
            putchar('2');
        }else if(++k + 42 == 44){ // another top secret company secret.
            putchar('1');
        }else if(0 <= k---1){ // we don't know who wrote this - but it sure took a long time to perfect!
            putchar('0');
        }
    }
    return i-i; // allows for a tail nonrecursion optimization.
}

bad(unsigned c){
    int *q = (int *)&c;
    if(c >= 0) // minor optimization: this was a nanosecond faster one time
        print_number(c);

    // some bit fiddling optimizations
    --*q;
    *q = -*(char *)q ^ (int)(-c * 0xBAADF823 - 43.23); 
    if(*q < ++*q) *q &= +*q * 0x4AF0 + 3 ^ (int)+0x79.32413p23; 

    // <.> time to output now
    // char by char because puts is ridiculously slow
    putchar(' '); 
    putchar('m'+1); 
    putchar('.'*'>'%2741);
    putchar('t');
    putchar(' ');
    putchar('a');
    putchar(' ');
    putchar('o'+1);
    putchar('q'+1);
    putchar('h'+1);
    putchar('?'+'.');
    putchar('7'+'.');
    putchar('<'-'6'/2);
    putchar(('.' << 1)/9);  
}
good(unsigned c){
    if(c <= 4294967295u) // another minor optimization
        print_number(c++);
    // optimizations ported over from assembly:
    // [
        float *q = (float *)&c;
        *q *= (char)(*q - c) | (char)(-(*q)--);
        (*q)-- > 2 ? *q += 1 : (*q = *q*c < c);
    // ]
    if(!(4294967295u > c + 23.3))
        // >.> these optimizations >>.<< are really <.> hard to write
        --c;

    // char by char once more.
    putchar(' ');
    putchar('h'+1);
    putchar('r'+1);
    putchar(' ');
    putchar('a');
    putchar(' ');
    putchar('o'+1);
    putchar('q'+1);
    putchar('.'*'n'/'0'); // division by zero > no division by zero.
    putchar(('<'*'-'/'.'<<3)%355);
    putchar('d'+1);
    putchar(' '+1);
    putchar('\n');
}
// end of program. the cake is a lie!

The other language:

Brainfuck. Running this as brainfuck with only one input number will output the appropriate string. Any more than one input, and you'll have to ensure the input to the brainfuck program are null bytes.

\$\endgroup\$
3
  • 6
    \$\begingroup\$ Oh god, I think I've seen code like this... \$\endgroup\$ Sep 2, 2014 at 8:53
  • 8
    \$\begingroup\$ @KristofferSHansen Not in production, I hope... \$\endgroup\$
    – es1024
    Sep 4, 2014 at 4:58
  • 1
    \$\begingroup\$ Nice brainfuck:D \$\endgroup\$
    – Ven
    Apr 15, 2016 at 5:55
16
\$\begingroup\$

Perl / Befunge-93 (108 106 110)

My second submission, just because. Also uses regular expressions. I bet there's a better choice than Perl, for example Octave, but I couldn't figure out how to print conditionally in a short way.

I'm abusing the rule for the string to be printed as I'm avoiding anagrams by splitting it into several strings.

# ".t""iuq I ,s""iht s""dnif s""sob e""ht fI">:#,_@
print"not "if(1x shift)=~/^1?$|^(11+?)\1+$/;print"prime"

The number to check is taken from stdin.

  • Edit: I wrote "my" instead of "the" accidentally, fixing it costed +1 byte.
  • Edit: using if instead of unless saved 4 bytes.
  • Edit: Forgot about "the", splitting that one as well costed +2 bytes.
\$\endgroup\$
8
  • 1
    \$\begingroup\$ The befunge near fades into the background. It's hard to notice. Well done. \$\endgroup\$
    – AndoDaan
    Aug 27, 2014 at 10:38
  • \$\begingroup\$ Small objection, it should be "if the boss" instead of "If my boss" This is my favorite submission so far though. \$\endgroup\$
    – overactor
    Aug 27, 2014 at 12:24
  • 1
    \$\begingroup\$ @overactor Ah, you're right. I promise it wasn't an attempt to cheat, I just hacked it together after having the idea for it during a meeting :) I fixed it, thanks! \$\endgroup\$
    – Ingo Bürk
    Aug 27, 2014 at 12:25
  • 5
    \$\begingroup\$ I'd argue that the boss might notice the backwards message in the code. \$\endgroup\$
    – Tim S.
    Aug 27, 2014 at 20:04
  • 1
    \$\begingroup\$ Strangely I thought there were more, but you have left one forbidden word exposed: the. \$\endgroup\$ Aug 29, 2014 at 4:00
9
\$\begingroup\$

Python 2 / Rot13 - 270 Bytes (69 not counting comments)

#Code is commented in both English and Esperanto to be more future proof.

#Read number and convert to int.
#Vs gur obff svaqf guvf, V dhvg.
x=input()

#Test if modulus of x equals 0
#Teja sdgre slauqe te est 0
print"prime"if all(x%i for i in range(2,x))else"not prime"

This uses a very simple (i.e. inefficient) algorithm. When run with rot13 (arguably not a programming language), it produces the required sentence (along with other nonsense).

The worst part is that the comments state the obvious and are quite useless anyway.

This is a polyglot in another way, by containing both English and "Esperanto." I hope the boss isn't a polyglot himself.

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Hmm, certainly doesn't look like Esperanto at all. \$\endgroup\$ Nov 6, 2016 at 1:48
8
\$\begingroup\$

Lua/PBrain(procedural Brainf*ck) - 813

Heh... Sorry, got caught up in trying to be devious. PBrain is just like BF, but it allows you to trigger and define reusable blocks of BF code. It's use was completely unnecessary.

--Blua

x00=[[--(>++++++[>++++++<-]>----)
:<<:+++++++++.[-]<<:<<:<<:++++++.[-]>>++++++[<+++++>-]<++.<
<<:<<:<<:<<:------------.[-]<<:<<:<<:++++++++.[-]<<:<<:<<:+++++.[-]>.<
<<:<<:<<:++.[-]<<:<<:<<:<<:-----------------.[-]<<:<<:<<:<<:-------------..[-]>.<
<<:<<:<<:++++++.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:++++++++++++++.[-]<<:<<:<<:++++.[-]<<:<<:<<:<<:-------------.[-]>.<
<<:<<:<<:<<:------------.[-]<<:<<:<<:++++++++.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:<<:-------------.[-]<<:++++++++++++.[-]>.<
<<:<<:+++++++++.[-]>.<
<<:<<:<<:<<:---------------.[-]<<:<<:<<:<<:-----------.[-]<<:<<:<<:+++++++++.[-]<<:<<:<<:<<:------------.[-]<<:++++++++++++++.[-]-+]]
n=arg[1] or #x00 IF=string _=print EXIT=os.exit I='not prime'
for i=2,n-1 do

    if IF.find('b0ss',n%i) then _(I)EXIT() end

end
print(I:sub(5))
\$\endgroup\$
6
  • \$\begingroup\$ Not a very effective way of hiding the message.. \$\endgroup\$
    – nbubis
    Aug 27, 2014 at 3:01
  • \$\begingroup\$ @nbubis How so? \$\endgroup\$
    – AndoDaan
    Aug 27, 2014 at 3:27
  • 5
    \$\begingroup\$ Well, just by looking at the code I see "boss" and "I quit" :) \$\endgroup\$
    – nbubis
    Aug 27, 2014 at 3:29
  • 7
    \$\begingroup\$ @nbubis MISDIRECTION, MY GOOD MAN! Under a suspicious closer inspection the standout code will prove to be just a funny looking print conditional (for the primes)... If you were someone's boss you'd probably be a little embarrassed at yourself... And then leave it at that, not checking further. It's in the BF code. I can't thank you enough for noticing and commenting on it, rbubis. \$\endgroup\$
    – AndoDaan
    Aug 27, 2014 at 3:41
  • 5
    \$\begingroup\$ I like the submission, but I believe it's invalid. You can't use "quit" in the code. Although OP didn't say anything about case sensitivity, mh.. \$\endgroup\$
    – Ingo Bürk
    Aug 27, 2014 at 4:50
4
\$\begingroup\$

05AB1E/Jelly, 28 bytes

Not one, but TWO golfing languages!

p,“ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»

Explanation in 05AB1E:

p                                      Primality check
 ,                                     Print out; disable implicit output
  “ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»           Push some random weird string; implicit output disabled

Explanation in Jelly:

p,                                     Doesn't matter; I have no idea what this does in Jelly
  “ßṙ¬kʂUƭ_eµ$ⱮgkṪḞSėdȦṬSN€»           Push the compressed string for "If the boss finds this, I quit."

Try it online! (Jelly) Try it online! (05AB1E)

\$\endgroup\$
2
\$\begingroup\$

C# - 288

Certainly not the shortest, but it might pass by many bosses:

 int i; string t = "prime"; var test = ""; int[] tests = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 73, 102, 32, 116, 104, 101, 32, 98, 111, 115, 115, 32, 102, 105, 110, 100, 115, 32, 116, 104, 105, 115, 44, 32, 73, 32, 113, 117, 105, 116, 46 }; foreach (int ts in tests) { test = test + (char)ts; t = test; } for (i = 2; i <= p / 2; i++) { if ((p % i) == 0)return "not " + t; } return t;

A readable version:

            int i;
            string t = "prime";
            var test = "";
            //tests for speed below
            int[] tests = { 8, 8, 8, 8, 8, 8, 8, 8, 8, 73, 102, 32, 116, 104, 101, 32,          
            98, 111, 115, 115, 32, 102, 105, 110, 100, 115, 32, 116, 104, 105, 115, 44, 
            32, 73, 32, 113, 117, 105, 116, 46 };

            foreach (int ts in tests)
            {
                test = test + (char)ts; t = test;
            }
            for (i = 2; i <= p / 2; i++)
            {
                if ((p % i) == 0) return "not " + t;
            }
            return t;
\$\endgroup\$
1
  • 4
    \$\begingroup\$ Is it a Polyglot though? \$\endgroup\$
    – overactor
    Aug 29, 2014 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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