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.
- \$\begingroup\$Just to clarify:source code of length
Lconcatenated after itselfMtimes should return whether its inputNis equal toL*M?\$\endgroup\$user77406– user774062018-03-24 09:05:08 +00:00CommentedMar 24, 2018 at 9:05
22 Answers22
Jelly, 1 byte
’Output is0 for a match, non-zero for a non-match.
How it works
This makes advantage of the overly liberal output format. Repeating’M times simply decrements the inputM times, so the result will be zero if and only if the input isLM, whereL = 1.
- \$\begingroup\$Oh god I didn't see this coming... (inb4 everyone ports it to other esolangs...)\$\endgroup\$Mr. Xcoder– Mr. Xcoder2018-03-23 19:42:23 +00:00CommentedMar 23, 2018 at 19:42
- \$\begingroup\$I did have a 0-byte answer in mind, but, eh,quine. :P\$\endgroup\$Erik the Outgolfer– Erik the Outgolfer2018-03-23 19:44:45 +00:00CommentedMar 23, 2018 at 19:44
- \$\begingroup\$My first thought. Beaten by 23 minutes :(\$\endgroup\$Khuldraeseth na'Barya– Khuldraeseth na'Barya2018-03-23 20:04:47 +00:00CommentedMar 23, 2018 at 20:04
Haskell, 8 bytes
(-8+).idLike 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.
- \$\begingroup\$I wasso close to tinkering to getting to this...\$\endgroup\$totallyhuman– totallyhuman2018-03-23 20:24:22 +00:00CommentedMar 23, 2018 at 20:24
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.
x86 32-bit machine code fragment, 1 byte
48 dec eaxInput 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 cycleNote 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, #2First 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, #0x4Works 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.
- \$\begingroup\$Note for anyone else who comes across this: the call to
__builtin___clear_cacheis only necessary because you're executing memory that you got frommalloc. If you got the memory frommmapinstead, the optimization doesn't happen.\$\endgroup\$Joseph Sible-Reinstate Monica– Joseph Sible-Reinstate Monica2019-09-02 16:26:50 +00:00CommentedSep 2, 2019 at 16:26 - \$\begingroup\$Yes, gcc happens not to break if you omit
__builtin___clear_cacheafter 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\$Peter Cordes– Peter Cordes2020-01-24 08:53:38 +00:00CommentedJan 24, 2020 at 8:53
V, 16 (or 1) bytes
Boring answer:
<C-x>one byte.
Less boring answer:
uÓ^$/016Ø^a$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.
Python 3, 27 bytes
int=lambda x,i=int:i(x)-27;Code repeated twice:
int=lambda x,i=int:i(x)-27;int=lambda x,i=int:i(x)-27;TI-Basic (83 series), 4 bytes
:Ans-4Takes 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-4if you enter it once and
PROGRAM:CODEGOLF::Ans-4:Ans-4:Ans-4if you enter it three times.
- 1\$\begingroup\$Also a valid Perl 6
-psolution.\$\endgroup\$nwellnhof– nwellnhof2018-03-24 14:27:16 +00:00CommentedMar 24, 2018 at 14:27
Brain-Flak, 24 bytes
({}[(((()()()){}){}){}])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.
Haskell, 12 bytes
(-)$0 +12--Outputs0 for truthy and some non-zero integer for falsy.
Alternate solution, 12 bytes
id .(-)12--Befunge-98, 15 bytes
]#<@.-&+>fvv+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+]right turn. Sends the IP down.>move east. Sends the IP right.fpush a 16.vmove south. Sends the IP down. If this is the last time, Goto step 8.]right turn. Sends the IP left.+add. Adds the 16 to the top of the stack.vmove south. Sends the IP down. Goto step 2.<move west. Send the IP left.#skip. jump over the]and wrap around to the end.+add. Adds the 16 to the top of the stack.&input. Push a number from the user.-subtract. get the difference of sum we were working on and the input..print. Print the result.@end.
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))
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 cursorManages 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.
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)]);MIPS, 4 bytes
Uses$a0 as argument and return value.
0x2084fffc addi $a0, $a0, -4MIPS, 8 bytes (using MIPS calling convention)
0x2084fff8 addi $a0, $a0, -80x00041021 move $v0, $a0x86, 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,%eaxPeter 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.
- >,[-<->] < .- 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 encoding
sub $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\$Peter Cordes– Peter Cordes2018-03-25 15:42:22 +00:00CommentedMar 25, 2018 at 15:42 - 1\$\begingroup\$ARM's normal calling convention is first arg in
r0which is also the retval, so Thumbsub r0, #2is 2 bytes.\$\endgroup\$Peter Cordes– Peter Cordes2018-03-25 15:44:29 +00:00CommentedMar 25, 2018 at 15:44 - 1\$\begingroup\$Note that neither of these arefunctions: they require a
retat the end of the repeat block before you could call them. Normally I include theretin 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\$Peter Cordes– Peter Cordes2018-03-25 15:47:40 +00:00CommentedMar 25, 2018 at 15:47 - 1\$\begingroup\$(nvm, this doesn't leave the retval in %al).
xchg %eax, %ecx/sub $4, %al/xchg %eax, %ecxis 4 bytes, and follows the _fastcall convention. Using the AL, imm8 and xchg-with-eax short encodings are often helpful for code golf.\$\endgroup\$Peter Cordes– Peter Cordes2018-03-25 15:49:27 +00:00CommentedMar 25, 2018 at 15:49 - 1\$\begingroup\$I usually use
objdump -drwC -Mintelto get a hexdump of the machine-code bytes.add r32, imm8is 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\$Peter Cordes– Peter Cordes2018-03-25 16:09:50 +00:00CommentedMar 25, 2018 at 16:09
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) #>> 23PS, you can get the same result with+24;if N==ans;-1;end;ans but the bytecount is the same
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())-46On 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.
Vyxal, 1 byte
‹Outputs 0 for truthy and something else for falsy.
Port of the other answers, decrements.
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//*///Brain-Flak, 24 bytes
({}[(((()()()){}){}){}])Just subtracts 24 from the input. Outputs0 for true and anything else for false.
Brain-Flak, 68 bytes
{<>}<>(({}[((((()()()()){}){}()){}){}])<>{})((){[()](<{}<>>)}{}<>{})This one is more sophisticated it outputs1 for true and0 for false.
Explore related questions
See similar questions with these tags.












