19
\$\begingroup\$

Your task is to write a non-empty program / function of byte countL, which, when repeatedM times, checks whether a given positive integerN is equal toL × M.

You should, in theory, support an arbitrary number of repetitions (an arbitrary positive integer value ofM), but it's fine if, due to language limitations, it cannot work over a certain threshold. Reading the source code of your program or accessing information about it isstrictly forbidden.

For providing output, you should choose a consistent value for one of the states (either truthy or falsy) and use any other (not necessarily consistent) possible output for the other state (Discussion).

Your answers will be scored by your initial program's lengthL (in bytes), with less bytes being better.

Example

Let's say your (initial) program isABCDE. Then:

  • ABCDE (1 repetition) should check if the input equals5.
  • ABCDEABCDE (2 repetitions) should check if the input equals10.
  • ABCDEABCDEABCDE (3 repetitions) should check if the input equals15. Etc...

The score of this sample code would be5, as the initial source is 5 bytes long.

Jo King's user avatar
Jo King
48.1k6 gold badges131 silver badges187 bronze badges
askedMar 23, 2018 at 19:10
Mr. Xcoder's user avatar
\$\endgroup\$
1
  • \$\begingroup\$Just to clarify:source code of lengthL concatenated after itselfM times should return whether its inputN is equal toL*M?\$\endgroup\$CommentedMar 24, 2018 at 9:05

22 Answers22

12
\$\begingroup\$

Jelly, 1 byte

Output is0 for a match, non-zero for a non-match.

Try it online!

How it works

This makes advantage of the overly liberal output format. RepeatingM times simply decrements the inputM times, so the result will be zero if and only if the input isLM, whereL = 1.

answeredMar 23, 2018 at 19:41
Dennis's user avatar
\$\endgroup\$
3
  • \$\begingroup\$Oh god I didn't see this coming... (inb4 everyone ports it to other esolangs...)\$\endgroup\$CommentedMar 23, 2018 at 19:42
  • \$\begingroup\$I did have a 0-byte answer in mind, but, eh,quine. :P\$\endgroup\$CommentedMar 23, 2018 at 19:44
  • \$\begingroup\$My first thought. Beaten by 23 minutes :(\$\endgroup\$CommentedMar 23, 2018 at 20:04
11
\$\begingroup\$

Haskell, 8 bytes

(-8+).id

Try it online!

Like many other answers it returns 0 for truthy and non-0 for falsy by repeatedly subtracting the length of the code from the input number.

answeredMar 23, 2018 at 20:23
nimi's user avatar
\$\endgroup\$
1
  • \$\begingroup\$I wasso close to tinkering to getting to this...\$\endgroup\$CommentedMar 23, 2018 at 20:24
8
\$\begingroup\$

Retina,21 20 bytes

\d+*^$_^_{20}_

Try it online! Just repeat the part in theCode window to see how it handles the multiples.

Gives0 for the correct multiple and positive integers for everything else.

Explanation

Let's look at the single program first:

\d+*

This converts a decimal number to unary (using_ as the unary digit).

^$_

If the string is empty (which can't happen at this point, because the input is guaranteed to be positive), we replace it with a single_.

^_{20}

Now we get rid of the first 20 underscores. Iff the input was20, this results in an empty string.

_

And finally we count the number of underscores in the result, which is zero iff the input was20.


Now what happens when we repeat the source code. Since we don't insert a linefeed when joining the programs, the first line will go right at the end of the last line, we get this when the double the program:

\d+*^$_^_{20}_\d+*^$_^_{20}_

Now instead of counting the underscores, we end up with the following stage:

_\d+*

This stage does nothing, because there are no more digits in the working string at this point, so the regex can't match.

^$_

Now this stage becomes relevant. If the input was a smaller multiple of 20, the string has been emptied by the previous copy of the source code. In that case, we turn it into a single underscore, which we know can never be turned into an empty string again by our program. This way we ensure thatonly theMth multiple is accepted (and not all multiples up to theMth).

^_{20}

We remove the first 20 underscores once more. SoM repetitions of the source code will remove20M underscores from the string, if possible.

_

And when we get to the end of the program, we still count underscores so that valid inputs give zero.

answeredMar 23, 2018 at 19:34
Martin Ender's user avatar
\$\endgroup\$
7
\$\begingroup\$

x86 32-bit machine code fragment, 1 byte

48                      dec    eax

Input in EAX, output in EAX: 0 for true, non-zero for false. (Also leaves the ZF flag set for true, unset for false, so you couldje was_equal). As a "bonus", you don't have to worry about wrapping; 32-bit x86 can only address 4GiB of memory, so you can't make M large enough to wrap all the way around and find1 == 2**32 + 1 or something.

To make a callable function, append a0xC3ret instruction after repeating0x48 M times. (Not counted in the total count, because many languages need to repeat just the function body, or an expression, to be able to compete).

Calleable from GNU C with the prototype__attribute__((regparm(1))) int checkeqM(int eax);GNU C'sregparm x86 function attribute, like-mregparm, uses EAX to pass the first integer arg.

For example, this complete program takes 2 args, and JITs M copies of the instruction + aret into a buffer, and then calls it as a function. (Requires executable heap; compile withgcc -O3 -m32 -z execstack)

/******* Test harness: JIT into a buffer and call it ******/// compile with gcc -O3 -no-pie -fno-pie -m32 -z execstack// or use mprotect or VirtualProtect instead of -z execstack// or mmap(PROT_EXEC|PROT_READ|PROT_WRITE) instead of malloc// declare a function pointer to a regparm=1 function// The special calling convention applies to this function-pointer only// So main() can still get its args properly, and call libc functions.// unlike if you compile with -mregparm=1typedef int __attribute__((regparm(1))) (*eax_arg_funcptr_t)(unsigned arg);#include <stdlib.h>#include <string.h>#include <stdio.h>int main(int argc, char *argv[]){    if (argc<3) return -1;    unsigned N=strtoul(argv[1], NULL, 0), M = strtoul(argv[2], NULL, 0);    char *execbuf = malloc(M+1);   // no error checking    memset(execbuf, 0x48, M);     // times M  dec eax    execbuf[M] = 0xC3;            // ret    // Tell GCC we're about to run this data as code.  x86 has coherent I-cache,    // but this also stops optimization from removing these as dead stores.    __builtin___clear_cache (execbuf, execbuf+M+1);     //   asm("" ::: "memory");  // compiler memory barrier works too.    eax_arg_funcptr_t execfunc = (eax_arg_funcptr_t) execbuf;    int res = execfunc(N);    printf("%u == %u  =>  %d\n", N,M, res );    return !!res;   // exit status only takes the low 8 bits of return value}

non-PIE executables are loaded lower in virtual memory; can do a bigger contiguous malloc.

$ gcc -g -O3 -m32 -no-pie -fno-pie -fno-plt -z execstack coderepeat-i386.c$ time ./a.out 2747483748 2747483748   # 2^31 + 600000100 is close to as big as we can allocate successfully2747483748 == 2747483748  =>  0real    0m1.590s     # on a 3.9GHz Skylake with DDR4-2666user    0m0.831ssys     0m0.755s$ echo $?0 # perf stat output:       670,816      page-faults               #    0.418 M/sec                   6,235,285,157      cycles                    #    3.885 GHz                     5,370,142,756      instructions              #    0.86  insn per cycle

Note thatGNU C doesn't support object sizes larger thanptrdiff_t (signed 32-bit), butmalloc andmemset do still work, so this program succeeds.

ARM Thumb machine code fragment, 2 bytes

 3802            subs    r0, #2

First arg inr0 and return value inr0 is the standard ARM calling convention. This also sets flags (thes suffix). Fun fact; thenon-flag-setting version ofsub is a 32-bit wide instruction.

The return instruction you need to append isbx lr.

AArch64 machine code fragment, 4 bytes

d1001000        sub     x0, x0, #0x4

Works for 64-bit integers. Input / output inx0, as per the standard calling convention.int64_t foo(uint64_t);

AArch64 doesn't have a Thumb mode (yet), so 1 instruction is the best we can do.

answeredMar 25, 2018 at 20:25
Peter Cordes's user avatar
\$\endgroup\$
2
  • \$\begingroup\$Note for anyone else who comes across this: the call to__builtin___clear_cache is only necessary because you're executing memory that you got frommalloc. If you got the memory frommmap instead, the optimization doesn't happen.\$\endgroup\$CommentedSep 2, 2019 at 16:26
  • \$\begingroup\$Yes, gcc happens not to break if you omit__builtin___clear_cache after writing into ammaped buffer. But only because gcc doesn't know aboutmmap(MAP_ANONYMOUS) and considers the stores a possibly visible side-effect that the called function might read. So it happens to work, but there's no reasonnot to follow the rules and tell the compiler that some stores are actually used, definitely not dead.\$\endgroup\$CommentedJan 24, 2020 at 8:53
4
\$\begingroup\$

V, 16 (or 1) bytes

Boring answer:

<C-x>

one byte.

Less boring answer:

uÓ^$/016Ø^a$

Try it online!

Hexdump:

00000000: 75d3 5e24 2f30 0a31 3601 d85e 1261 240a  u.^$/0.16..^.a$.

I actually wrote this about 5 minutes after the challenge came out. It took me 30 minutes to patch this horrible pile of spaghetti code that I call alanguage.

answeredMar 23, 2018 at 19:49
DJMcMayhem's user avatar
\$\endgroup\$
4
\$\begingroup\$

Python 3, 27 bytes

int=lambda x,i=int:i(x)-27;

Try it online!

Code repeated twice:

int=lambda x,i=int:i(x)-27;int=lambda x,i=int:i(x)-27;

Try it online!

answeredMar 24, 2018 at 23:23
Luca Citi's user avatar
\$\endgroup\$
3
\$\begingroup\$

TI-Basic (83 series), 4 bytes

:Ans-4

Takes input inAns: for example, you might type17:prgmCODEGOLF to run this with an input of17. Prints (and returns inAns) the value0 if the input is equal toL × M, and a nonzero value otherwise.

Note that the: is part of the code, so if you are entering this into the program editor, you should see

PROGRAM:CODEGOLF::Ans-4

if you enter it once and

PROGRAM:CODEGOLF::Ans-4:Ans-4:Ans-4

if you enter it three times.

answeredMar 23, 2018 at 20:41
Misha Lavrov's user avatar
\$\endgroup\$
3
\$\begingroup\$

Perl 5-p, 6 bytes

$_-=6;

Try it online!

uses0 for equal

answeredMar 23, 2018 at 20:42
Ton Hospel's user avatar
\$\endgroup\$
1
  • 1
    \$\begingroup\$Also a valid Perl 6-p solution.\$\endgroup\$CommentedMar 24, 2018 at 14:27
3
\$\begingroup\$
answeredMar 24, 2018 at 15:43
Erik the Outgolfer's user avatar
\$\endgroup\$
2
\$\begingroup\$

Brain-Flak, 24 bytes

({}[(((()()()){}){}){}])

Try it online!

Returns0 for equal and something else for not equal.

How it works:

({} #pop the top of the stack  [(((()()()){}){}){}] #subtract 24) #push the result.

This code runn times will subtractn * 24 from the input, giving 0 only when the input =n*24.

answeredMar 23, 2018 at 19:39
MegaTom's user avatar
\$\endgroup\$
2
\$\begingroup\$
answeredMar 23, 2018 at 19:48
\$\endgroup\$
1
\$\begingroup\$

Haskell, 12 bytes

(-)$0 +12--

Try it online!

Outputs0 for truthy and some non-zero integer for falsy.

Alternate solution, 12 bytes

id .(-)12--

Try it online!

answeredMar 23, 2018 at 19:50
totallyhuman's user avatar
\$\endgroup\$
1
\$\begingroup\$

Befunge-98, 15 bytes

]#<@.-&+>fvv+

Try it online!

Try it doubled!

Uses 0 for equal and anything else for unequal.

Explanation:

This code repeated many times will look something like this:

]#<@.-&+>fvv+]#<@.-&+>fvv+]#<@.-&+>fv . . .v+]#<@.-&+>fvv+
  1. ] right turn. Sends the IP down.

  2. > move east. Sends the IP right.

  3. f push a 16.

  4. v move south. Sends the IP down. If this is the last time, Goto step 8.

  5. ] right turn. Sends the IP left.

  6. + add. Adds the 16 to the top of the stack.

  7. v move south. Sends the IP down. Goto step 2.

  8. < move west. Send the IP left.

  9. # skip. jump over the] and wrap around to the end.

  10. + add. Adds the 16 to the top of the stack.

  11. & input. Push a number from the user.

  12. - subtract. get the difference of sum we were working on and the input.

  13. . print. Print the result.

  14. @ end.

answeredMar 23, 2018 at 20:33
MegaTom's user avatar
\$\endgroup\$
1
\$\begingroup\$

Pure Bash, 15

Input given as a command-line parameter. Output as a shell exit code -1 for TRUE and0 for FALSE.

(((a+=15)-$1))
answeredMar 23, 2018 at 22:31
Digital Trauma's user avatar
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 13 bytes

PI⁼Iθ×¹³L⊞Oυω

Try it online! Based on my answer toI double the source, you double the output! Explanation:

         ⊞Oυω   Push empty string to predefined empty list        L       Take the length     ×¹³        Multiply by 13  ⁼Iθ           Compare to the input I              Cast to stringP               Print without moving the cursor

Manages to output1 for truthy and0 for falsy. Subsequent repetitions compare the input against13,26,39,52 etc. but each time the answer is overprinted so only the final answer is seen.

answeredMar 23, 2018 at 23:32
Neil's user avatar
\$\endgroup\$
1
\$\begingroup\$

JavaScript ES6, 32 Bytes

((f=k=>n=>n>0?n==k:f(k+32))(32))

if true be 0 and false as others, 31 bytes

(f=k=>n=>n>0?n-k:_=>f(k+_))(31)

console.log([    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (31),    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (32),    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (33),    ((f=k=>n=>n>0?n==k:f(k+32))(32)) (64),    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (32),    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (63),    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (64),    ((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32))((f=k=>n=>n>0?n==k:f(k+32))(32)) (96)]);

answeredMar 24, 2018 at 16:15
l4m2's user avatar
\$\endgroup\$
1
\$\begingroup\$

MIPS, 4 bytes

Uses$a0 as argument and return value.

0x2084fffc    addi $a0, $a0, -4

MIPS, 8 bytes (using MIPS calling convention)

0x2084fff8    addi $a0, $a0, -80x00041021    move $v0, $a0

x86, 5 bytes

This is my first x86 answer so feedback welcome. Uses _fastcall convention with ecx as first argument.

83 e9 05                sub    $0x5,%ecx89 c8                   mov    %ecx,%eax

Peter Cordes has a 1 byte solution in the comments.


Brainfuck commentary: The hard part is getting brainfuck to return a single value. Otherwise something like this would be easy.

- >,[-<->] < .
answeredMar 24, 2018 at 19:50
qwr's user avatar
\$\endgroup\$
11
  • 1
    \$\begingroup\$Your x86 code fragment would be the same size for 32-bit integers, no need to limit to 8. But if you used a custom calling convention (arg in AL, retval somewhere else,), you could use the 2-byte AL special encodingsub $4, %al /mov %al, %dl. Or still return in AL/EAX and then you get Dennis's solution, withdec %eax (1 byte in 32-bit mode). And yes, custom calling conventions are fine for asm. It's asm, not just "asm that's easy to call from C"; real code written in asm does use custom calling conventions where it helps, so this is totally justifiable.\$\endgroup\$CommentedMar 25, 2018 at 15:42
  • 1
    \$\begingroup\$ARM's normal calling convention is first arg inr0 which is also the retval, so Thumbsub r0, #2 is 2 bytes.\$\endgroup\$CommentedMar 25, 2018 at 15:44
  • 1
    \$\begingroup\$Note that neither of these arefunctions: they require aret at the end of the repeat block before you could call them. Normally I include theret in byte counts for my x86 asm answers. But I think bending the rules here to just the functionbody makes sense, otherwise many languages can't compete at all.\$\endgroup\$CommentedMar 25, 2018 at 15:47
  • 1
    \$\begingroup\$(nvm, this doesn't leave the retval in %al).xchg %eax, %ecx /sub $4, %al /xchg %eax, %ecx is 4 bytes, and follows the _fastcall convention. Using the AL, imm8 and xchg-with-eax short encodings are often helpful for code golf.\$\endgroup\$CommentedMar 25, 2018 at 15:49
  • 1
    \$\begingroup\$I usually useobjdump -drwC -Mintel to get a hexdump of the machine-code bytes.add r32, imm8 is also 3 bytes: opcode + ModR/M + imm8. All instructions that can take an imm32 have an alternative opcode that takes a sign-extended imm8. Seefelixcloutier.com/x86/ADD.html for example; all the "classic" ALU instructions (but not MOV) that date back to 8086 have all those encodings, including the special AL/AX/EAX ones with no modr/m, just op + imm8/16/32.This answer has examples\$\endgroup\$CommentedMar 25, 2018 at 16:09
1
\$\begingroup\$

Octave: 23 bytes

+23;[ans,i]((N==ans)+1)

If N = L*M, the expression returns0+i (i.e. a purely imaginary number), otherwise the expression results in a complex number with a real component.

For a slightly nicer result at the cost of an extra byte:

+24;[ans,-1]((N==ans)+1)

If N = L*M the expression returns-1, otherwise a positive number.

Demo:

N=48;+24;[ans,-1]((N==ans)+1)                                                 #>> 24 +24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1)                         #>> -1+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1)+24;[ans,-1]((N==ans)+1) #>> 23

PS, you can get the same result with+24;if N==ans;-1;end;ans but the bytecount is the same

answeredMar 30, 2018 at 13:07
Tasos Papastylianou's user avatar
\$\endgroup\$
1
\$\begingroup\$

Lua,56 46 bytes

a=(a or io.read())-46io.write(a<=0 and a or"")

Outputs a 0 (without a trailing newline) if equal and either nothing or a series of negative numbers (with preceding zero in some cases) if not equal.

Alone:Try it online!

Repeated a bunch of times:Try it online!

Explanation

a=(a or io.read())-46

On the first iteration (whena hasn't been defined yet and is thereforenil), setsa to a number taken from input, otherwise to itself. In both cases, 46 is then subtracted froma.

io.write(a<=0 and a or"")

This just printsa if it is less than (to take care of cases where the input was larger than the total length) or equal to zero, and the empty string otherwise.

-10 bytes for remembering that Lua does conversions between numbers and strings automatically. Whoops.

answeredMar 23, 2018 at 20:53
ivzem's user avatar
\$\endgroup\$
1
\$\begingroup\$

Vyxal, 1 byte

Try it Online!

Outputs 0 for truthy and something else for falsy.

Port of the other answers, decrements.

answeredNov 18, 2021 at 7:15
emanresu A's user avatar
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 47 bytes

This is using the same technique asBenoit Esnard inthis answer (fromI double the source, you double the output!).

Prints0 ifn = 47 * M, or a non-zero value otherwise.

n=prompt(setTimeout`alert(n)`)-47/*n-=47//*///

Demo for M = 1

n=prompt(setTimeout`alert(n)`)-47/*n-=47//*///

Demo for M = 2

n=prompt(setTimeout`alert(n)`)-47/*n-=47//*///n=prompt(setTimeout`alert(n)`)-47/*n-=47//*///

answeredMar 23, 2018 at 22:27
Arnauld's user avatar
\$\endgroup\$
0
\$\begingroup\$

Brain-Flak, 24 bytes

({}[(((()()()){}){}){}])

Try it online!

Just subtracts 24 from the input. Outputs0 for true and anything else for false.

Brain-Flak, 68 bytes

{<>}<>(({}[((((()()()()){}){}()){}){}])<>{})((){[()](<{}<>>)}{}<>{})

Try it online!

This one is more sophisticated it outputs1 for true and0 for false.

answeredJun 27, 2018 at 3:49
Wheat Wizard's user avatar
\$\endgroup\$

Your Answer

More generally…

  • …Please make sure to answer the question and provide sufficient detail.

  • …Avoid asking for help, clarification or responding to other answers (use comments instead).

Draft saved
Draft discarded

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.