问:
Validating a CPR number

Validating a CPR number

A Danish CPR number (Person Identification Number) is date of birth followed by 4 digits (the last one being a control digit): DDMMYY-XXXX

The final digit validates the CPR number using Modulo 11 by satisfying the following equation:

where the  are the ten digits of the complete ID number, and the coefficients (4, 3, 2, 7, …) are all nonzero in the finite field of order 11.

Input

A CPR number formatted like this DDMMYY-XXXX where YY indicates a year within the last 100 years (between 1917 and 2016).

Output

Indication whether CPR number is valid (1 or true) or invalid (0 or false)

Examples

```<code>  290215-2353 --> false
  140585-2981 --> true
  311217-6852 --> true
  121200-0004 --> false
  140322-5166 --> false
  111111-1118 --> true
</code>```

Scoring

This is code-golf - fewest bytes win!

Date validation

All years refer to a period within the last 100 years. A valid date is a date that exists within it's calendar year.

290215 is not a valid date because 29/2 wasn't a date in 2015.

301216 is a valid date because 30/12 is a date in 2016.

答:
Ruby, <s>145</s> <s>113</s> <s>112</s> 103 + 8 (-nrdate flags) = 111 bytes

Returns a date object (truthy) if it's a valid CPR, false if it fails the modulo test, and nil (falsy) if it fails the date test. Input is STDIN.

-33 bytes from @Jordan

```<code>s=0
$_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i}
p s%11<1&&Date.strptime($_,"%d%m%y")rescue p p
</code>```

Version that returns literal true on valid CPR for +1 byte:

```<code>s=0
$_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i}
p Date.strptime($_,"%d%m%y")&&s%11<1 rescue p p
</code>```

Version that returns an error on invalid date instead of nil, for -10 bytes but probably invalid:

```<code>s=0
$_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i}
p Date.strptime($_,"%d%m%y")&&s%11<1
</code>```

Title: Validating a CPR number

Body:
Ruby, <s>145</s> <s>113</s> <s>112</s> 103 + 8 (-nrdate flags) = 111 bytes

Returns a date object (truthy) if it's a valid CPR, false if it fails the modulo test, and nil (falsy) if it fails the date test. Input is STDIN.

-33 bytes from @Jordan

s=0
$_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i}
p s%11<1&&Date.strptime($_,"%d%m%y")rescue p p

Version that returns literal true on valid CPR for +1 byte:

s=0
$_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i}
p Date.strptime($_,"%d%m%y")&&s%11<1 rescue p p

Version that returns an error on invalid date instead of nil, for -10 bytes but probably invalid:

s=0
$_.size.times{|i|s+=12340567234/10**i%10*$_[i].to_i}
p Date.strptime($_,"%d%m%y")&&s%11<1


问:
Divisibility test

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 3 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
MATL, 2 bytes

```<code>\~
</code>```

Try it online!

```<code>\    % Take two inputs implicitly. Compute their modulo
~    % Logical negate. Implicit display
</code>```

ContentLicense: CC BY-SA 3.0

Title: Divisibility test

Body:
MATL, 2 bytes

\~

Try it online!

\    % Take two inputs implicitly. Compute their modulo
~    % Logical negate. Implicit display


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

This is code-golf, so shortest answer in bytes wins!

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Title: Print numbers from 1 to 10

Body:
JS, 75 Bytes

a=[0,1,2,3,4,5,6,7,8,9,10]; for(a[0];a[0]<a.length;a[0]++){alert(a[a[0]]);}


问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Sesos, 63 62 58 bytes

```<code>0000000: 1651bc afcddc c4fbbe 3e739e c0f1be 3673c3 eecdf8  .Q.......>s....6s....
0000015: cc75b8 677ce2 b57bc6 78cddc 796de3 7eed33 b7c113  .u.g|..{.x..ym.~.3...
000002a: ef9da3 a0fbbc 77ece7 3adc2b 354e33 f9             ......w..:.+5N3.
</code>```

The ASM code that I wrote, along with some comments can be run on Try it online:

```<code>set numin
set numout
get
sub 1
jmp ; if
    add 1
    jmp ; copy
        fwd 1
        add 1
        fwd 1
        add 1
        rwd 2
        sub 1
    jnz ; end copy
    fwd 2
    sub 1
    jmp ; triplicate loop
        fwd 1
        add 1
        fwd 1
        add 1
        fwd 1
        add 1
        rwd 3
        sub 1
    jnz ; end triplicate
    fwd 1
    sub 1
    fwd 1
    sub 1
    jmp ; factorial loop
        jmp ; multiply loop
            fwd 1
            jmp ; forward add step of multiply loop
                fwd 1
                add 1
                fwd 1
                add 1
                rwd 2
                sub 1
            jnz ; end forward add step of multiply loop
            fwd 2
            jmp ; after add step, reset tape
                rwd 2
                add 1
                fwd 2
                sub 1
            jnz ; end reset tape
            rwd 3
            sub 1
        jnz ; end multiply
        fwd 1
        get ; sets to 0
        fwd 1
        jmp ; transfer intermediate value
            rwd 1
            add 1
            fwd 1
            sub 1
        jnz ; end transfer
        rwd 3
        sub 1
        jmp ; reset loop counter
            fwd 1
            add 1
            rwd 2
            add 1
            fwd 1
            sub 1
        jnz ; end reset
        rwd 1
        jmp ; fix memory location of header
            fwd 1
            add 1
            rwd 1
            sub 1
        jnz ; end fix
        fwd 2
    jnz ; end factorial
    fwd 1
    add 1
    rwd 4
    jmp ; transfer input for mod
        fwd 5
        add 1
        rwd 5
        sub 1
    jnz ; end transfer
    fwd 4
    jmp ; mod
        sub 1
        fwd 1
        sub 1
        jmp ; a
        fwd 1
        add 1
        fwd 2
        jnz ; a
        fwd 1
        jmp ; b
        add 1
        jmp ; c
        sub 1
        rwd 1
        add 1
        fwd 1
        jnz ; b
        fwd 1
        add 1
        fwd 2
        jnz ; c
        rwd 5
    jnz ; end mod
    fwd 1
    get ; sets to zero
    fwd 1
    jmp ; invert a
        rwd 1
        add 1
        fwd 1
        get ; blanks
    jnz ; end invert a
    add 1
    rwd 1
    jmp ; invert b
        fwd 1
        sub 1
        rwd 1
        sub 1
    jnz ; end invert b
jnz ; end if
fwd 1
put
</code>```

I've never written any BF variant code before, outside of very simple tasks, so I'm sure some of this is not optimal. The divmod algorithm and the logical negation algorithm used were taken from the esolangs algorithms page.

This implements Wilson's theorem. We compute (n-1)! + 1 and then logically negate that value mod n. The factorial code hangs on input 1, so the code is wrapped in an if loop that totally skips running in that case. At the very end, the tape head is manipulated to be over where we would have left the mod value if we ran the code, or over some random zero if the input was 1. I'll add a more thorough explanation when I am done golfing.

Title: Is this number a prime?

Body:
Sesos, 63 62 58 bytes

0000000: 1651bc afcddc c4fbbe 3e739e c0f1be 3673c3 eecdf8  .Q.......>s....6s....
0000015: cc75b8 677ce2 b57bc6 78cddc 796de3 7eed33 b7c113  .u.g|..{.x..ym.~.3...
000002a: ef9da3 a0fbbc 77ece7 3adc2b 354e33 f9             ......w..:.+5N3.

The ASM code that I wrote, along with some comments can be run on <a href="http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CnN1YiAxCmptcCA7IGlmCiAgICBhZGQgMQogICAgam1wIDsgY29weQogICAgICAgIGZ3ZCAxCiAgICAgICAgYWRkIDEKICAgICAgICBmd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgcndkIDIKICAgICAgICBzdWIgMQogICAgam56IDsgZW5kIGNvcHkKICAgIGZ3ZCAyCiAgICBzdWIgMQogICAgam1wIDsgdHJpcGxpY2F0ZSBsb29wCiAgICAgICAgZndkIDEKICAgICAgICBhZGQgMQogICAgICAgIGZ3ZCAxCiAgICAgICAgYWRkIDEKICAgICAgICBmd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgcndkIDMKICAgICAgICBzdWIgMQogICAgam56IDsgZW5kIHRyaXBsaWNhdGUKICAgIGZ3ZCAxCiAgICBzdWIgMQogICAgZndkIDEKICAgIHN1YiAxCiAgICBqbXAgOyBmYWN0b3JpYWwgbG9vcAogICAgICAgIGptcCA7IG11bHRpcGx5IGxvb3AKICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgam1wIDsgZm9yd2FyZCBhZGQgc3RlcCBvZiBtdWx0aXBseSBsb29wCiAgICAgICAgICAgICAgICBmd2QgMQogICAgICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgICAgIGZ3ZCAxCiAgICAgICAgICAgICAgICBhZGQgMQogICAgICAgICAgICAgICAgcndkIDIKICAgICAgICAgICAgICAgIHN1YiAxCiAgICAgICAgICAgIGpueiA7IGVuZCBmb3J3YXJkIGFkZCBzdGVwIG9mIG11bHRpcGx5IGxvb3AKICAgICAgICAgICAgZndkIDIKICAgICAgICAgICAgam1wIDsgYWZ0ZXIgYWRkIHN0ZXAsIHJlc2V0IHRhcGUKICAgICAgICAgICAgICAgIHJ3ZCAyCiAgICAgICAgICAgICAgICBhZGQgMQogICAgICAgICAgICAgICAgZndkIDIKICAgICAgICAgICAgICAgIHN1YiAxCiAgICAgICAgICAgIGpueiA7IGVuZCByZXNldCB0YXBlCiAgICAgICAgICAgIHJ3ZCAzCiAgICAgICAgICAgIHN1YiAxCiAgICAgICAgam56IDsgZW5kIG11bHRpcGx5CiAgICAgICAgZndkIDEKICAgICAgICBnZXQgOyBzZXRzIHRvIDAKICAgICAgICBmd2QgMQogICAgICAgIGptcCA7IHRyYW5zZmVyIGludGVybWVkaWF0ZSB2YWx1ZQogICAgICAgICAgICByd2QgMQogICAgICAgICAgICBhZGQgMQogICAgICAgICAgICBmd2QgMQogICAgICAgICAgICBzdWIgMQogICAgICAgIGpueiA7IGVuZCB0cmFuc2ZlcgogICAgICAgIHJ3ZCAzCiAgICAgICAgc3ViIDEKICAgICAgICBqbXAgOyByZXNldCBsb29wIGNvdW50ZXIKICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgcndkIDIKICAgICAgICAgICAgYWRkIDEKICAgICAgICAgICAgZndkIDEKICAgICAgICAgICAgc3ViIDEKICAgICAgICBqbnogOyBlbmQgcmVzZXQKICAgICAgICByd2QgMQogICAgICAgIGptcCA7IGZpeCBtZW1vcnkgbG9jYXRpb24gb2YgaGVhZGVyCiAgICAgICAgICAgIGZ3ZCAxCiAgICAgICAgICAgIGFkZCAxCiAgICAgICAgICAgIHJ3ZCAxCiAgICAgICAgICAgIHN1YiAxCiAgICAgICAgam56IDsgZW5kIGZpeAogICAgICAgIGZ3ZCAyCiAgICBqbnogOyBlbmQgZmFjdG9yaWFsCiAgICBmd2QgMQogICAgYWRkIDEKICAgIHJ3ZCA0CiAgICBqbXAgOyB0cmFuc2ZlciBpbnB1dCBmb3IgbW9kCiAgICAgICAgZndkIDUKICAgICAgICBhZGQgMQogICAgICAgIHJ3ZCA1CiAgICAgICAgc3ViIDEKICAgIGpueiA7IGVuZCB0cmFuc2ZlcgogICAgZndkIDQKICAgIGptcCA7IG1vZAogICAgICAgIHN1YiAxCiAgICAgICAgZndkIDEKICAgICAgICBzdWIgMQogICAgICAgIGptcCA7IGEKICAgICAgICBmd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgZndkIDIKICAgICAgICBqbnogOyBhCiAgICAgICAgZndkIDEKICAgICAgICBqbXAgOyBiCiAgICAgICAgYWRkIDEKICAgICAgICBqbXAgOyBjCiAgICAgICAgc3ViIDEKICAgICAgICByd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgZndkIDEKICAgICAgICBqbnogOyBiCiAgICAgICAgZndkIDEKICAgICAgICBhZGQgMQogICAgICAgIGZ3ZCAyCiAgICAgICAgam56IDsgYwogICAgICAgIHJ3ZCA1CiAgICBqbnogOyBlbmQgbW9kCiAgICBmd2QgMQogICAgZ2V0IDsgc2V0cyB0byB6ZXJvCiAgICBmd2QgMQogICAgam1wIDsgaW52ZXJ0IGEKICAgICAgICByd2QgMQogICAgICAgIGFkZCAxCiAgICAgICAgZndkIDEKICAgICAgICBnZXQgOyBibGFua3MKICAgIGpueiA7IGVuZCBpbnZlcnQgYQogICAgYWRkIDEKICAgIHJ3ZCAxCiAgICBqbXAgOyBpbnZlcnQgYgogICAgICAgIGZ3ZCAxCiAgICAgICAgc3ViIDEKICAgICAgICByd2QgMQogICAgICAgIHN1YiAxCiAgICBqbnogOyBlbmQgaW52ZXJ0IGIKam56IDsgZW5kIGlmCmZ3ZCAxCnB1dA&input=Nw" rel="nofollow">Try it online:

set numin
set numout
get
sub 1
jmp ; if
    add 1
    jmp ; copy
        fwd 1
        add 1
        fwd 1
        add 1
        rwd 2
        sub 1
    jnz ; end copy
    fwd 2
    sub 1
    jmp ; triplicate loop
        fwd 1
        add 1
        fwd 1
        add 1
        fwd 1
        add 1
        rwd 3
        sub 1
    jnz ; end triplicate
    fwd 1
    sub 1
    fwd 1
    sub 1
    jmp ; factorial loop
        jmp ; multiply loop
            fwd 1
            jmp ; forward add step of multiply loop
                fwd 1
                add 1
                fwd 1
                add 1
                rwd 2
                sub 1
            jnz ; end forward add step of multiply loop
            fwd 2
            jmp ; after add step, reset tape
                rwd 2
                add 1
                fwd 2
                sub 1
            jnz ; end reset tape
            rwd 3
            sub 1
        jnz ; end multiply
        fwd 1
        get ; sets to 0
        fwd 1
        jmp ; transfer intermediate value
            rwd 1
            add 1
            fwd 1
            sub 1
        jnz ; end transfer
        rwd 3
        sub 1
        jmp ; reset loop counter
            fwd 1
            add 1
            rwd 2
            add 1
            fwd 1
            sub 1
        jnz ; end reset
        rwd 1
        jmp ; fix memory location of header
            fwd 1
            add 1
            rwd 1
            sub 1
        jnz ; end fix
        fwd 2
    jnz ; end factorial
    fwd 1
    add 1
    rwd 4
    jmp ; transfer input for mod
        fwd 5
        add 1
        rwd 5
        sub 1
    jnz ; end transfer
    fwd 4
    jmp ; mod
        sub 1
        fwd 1
        sub 1
        jmp ; a
        fwd 1
        add 1
        fwd 2
        jnz ; a
        fwd 1
        jmp ; b
        add 1
        jmp ; c
        sub 1
        rwd 1
        add 1
        fwd 1
        jnz ; b
        fwd 1
        add 1
        fwd 2
        jnz ; c
        rwd 5
    jnz ; end mod
    fwd 1
    get ; sets to zero
    fwd 1
    jmp ; invert a
        rwd 1
        add 1
        fwd 1
        get ; blanks
    jnz ; end invert a
    add 1
    rwd 1
    jmp ; invert b
        fwd 1
        sub 1
        rwd 1
        sub 1
    jnz ; end invert b
jnz ; end if
fwd 1
put

I've never written any BF variant code before, outside of very simple tasks, so I'm sure some of this is not optimal. The divmod algorithm and the logical negation algorithm used were taken from the esolangs algorithms page.

This implements Wilson's theorem. We compute (n-1)! + 1 and then logically negate that value mod n. The factorial code hangs on input 1, so the code is wrapped in an if loop that totally skips running in that case. At the very end, the tape head is manipulated to be over where we would have left the mod value if we ran the code, or over some random zero if the input was 1. I'll add a more thorough explanation when I am done golfing.


问:
Calculate the Super-Logarithm
This should be a simple challenge.

Given a number \$n \ge 0\$, output the super-logarithm (or the \$\log^*\$, log-star, or iterated logarithm, which are equivalent since \$n\$ is never negative for this challenge.) of \$n\$.

$$\log^*(n) = \begin{cases}
0  & \text{ if } n \le 1 \\
1 + \log^*(\log(n)) & \text{ if } n > 1
\end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

Examples

```<code>Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4
</code>```

Rules

You do not need to support decimals, though you may.

You need to support input of at least \$3814280 =  \left\lceil e^{e^e} \right\rceil\$.

You may not hard-code the values like 3814280. (Your program must theoretically support higher numbers.) I want an algorithm to be implemented.

Shortest code wins.

Related OEIS

ContentLicense: CC BY-SA 4.0

Title: Calculate the Super-Logarithm

Body:
Racket, 61 bytes

(λ(x)(letrec([a(λ(b)(if(> b 1)(+ 1 (a(log b)))0))])(a x)))


问:
Count of "a"s and "b"s must be equal. Did you get it computer?
In the popular (and essential) computer science book, An Introduction to Formal Languages and Automata by Peter Linz, the following formal language is frequently stated:

$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$

mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".

Challenge

Write a working program/function which gets a string, containing "a"s and "b"s only, as input and returns/outputs a truth value, saying if this string is valid the formal language L.

Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.

Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. More info here.

Standard code golf rules apply.

This is a code-golf. Shortest code in bytes wins. Good luck!

Truthy test cases

```<code>"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
</code>```

Falsy test cases

```<code>""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
</code>```

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 85994; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
JavaScript, 34 bytes

```<code>s=>(s=s.match`^a(.*)b$`[1])?f(s):1
</code>```

In true automata fashion, this function returns 1 if it's true, and fails if it's not.

f=s=>(s=s.match`^a(.*)b$`[1])?f(s):1

let test_strings = ["ab", "aabb", "", "a", "abb", "abc", "abab", "abba"];
test_strings.map(s => {
try {console.log("f(\"" + s + "\") returned " + f(s));}
catch(e) {console.log("f(\"" + s + "\") threw " + e);}
});```

Body:
JavaScript, 34 bytes

s=>(s=s.match`^a(.*)b$`[1])?f(s):1

In true automata fashion, this function returns 1 if it's true, and fails if it's not.

f=s=>(s=s.match`^a(.*)b$`[1])?f(s):1

let test_strings = ["ab", "aabb", "", "a", "abb", "abc", "abab", "abba"];
test_strings.map(s => {
try {console.log("f(\"" + s + "\") returned " + f(s));}
catch(e) {console.log("f(\"" + s + "\") threw " + e);}
});


答:
Ruby + GNU date, 112 111 103 bytes

-8 bytes from Kevin Lau.

```<code>->n{s=0
n.size.times{|i|s+=12340567234/10**i%10*n[i].to_i}
n=~/#{"(..)"*3}/
s%11<1&&`date -d#$3#$2#$1`>""}
</code>```

Note that this prints e.g. "date: invalid date ‘150229’" to stderr if the date portion is invalid, but it still returns true or false (it doesn't raise an exception). If that's a disqualifier, though, I can add ⎵2>/dev/null for a 12-byte penalty.

Ungolfed

```<code>v = ->(cpr) {
  sum = 0

  cpr.size.times do |idx|
    sum += 12340567234 / 10**idx % 10 * cpr[idx].to_i
  end

  cpr =~ /#{"(..)" * 3}/
  sum % 11 < 1 && `date -d#$3#$2#$1` > ""
}
</code>```

Title: Validating a CPR number

Body:
Validating a CPR number

A Danish CPR number (Person Identification Number) is date of birth followed by 4 digits (the last one being a control digit): DDMMYY-XXXX

The final digit validates the CPR number using Modulo 11 by satisfying the following equation:

where the  are the ten digits of the complete ID number, and the coefficients (4, 3, 2, 7, …) are all nonzero in the finite field of order 11.

Input

A CPR number formatted like this DDMMYY-XXXX where YY indicates a year within the last 100 years (between 1917 and 2016).

Output

Indication whether CPR number is valid (1 or true) or invalid (0 or false)

Examples

```<code>  290215-2353 --> false
  140585-2981 --> true
  311217-6852 --> true
  121200-0004 --> false
  140322-5166 --> false
  111111-1118 --> true
</code>```

Scoring

This is code-golf - fewest bytes win!

Date validation

All years refer to a period within the last 100 years. A valid date is a date that exists within it's calendar year.

290215 is not a valid date because 29/2 wasn't a date in 2015.

301216 is a valid date because 30/12 is a date in 2016.

Body:
Ruby + GNU date, 112 111 103 bytes

-8 bytes from Kevin Lau.

->n{s=0
n.size.times{|i|s+=12340567234/10**i%10*n[i].to_i}
n=~/#{"(..)"*3}/
s%11<1&&`date -d#$3#$2#$1`>""}

Note that this prints e.g. "date: invalid date ‘150229’" to stderr if the date portion is invalid, but it still returns true or false (it doesn't raise an exception). If that's a disqualifier, though, I can add ⎵2>/dev/null for a 12-byte penalty.

Ungolfed

v = ->(cpr) {
  sum = 0

  cpr.size.times do |idx|
    sum += 12340567234 / 10**idx % 10 * cpr[idx].to_i
  end

  cpr =~ /#{"(..)" * 3}/
  sum % 11 < 1 && `date -d#$3#$2#$1` > ""
}


问:
Transposed, primes, oh my!
The task is simple: your program reads an integer as an input, and prints whether it is a prime or not. You can print "yes/no", "true/false" or anything what unambiguously identifies the result.

The challenge is, the code has to work with its rows and columns transposed.

To exclude the obvious solution (shortest "simple" solution repeated vertically char-by-char with the use of comments), the metric is a little bit different from the usual code-golf:

Because formatting is very important in this challenge, the code size is measured in the area of the smallest rectangle the code fits in. In other words, whitespace does count, and the lines should be filled to be of equal length (you don't have to actually do it when you post the solution, for simplicity's sake). For example

```<code>int main()
{
    return 0;
}
</code>```

would have a size of 4*13 = 52, (and obviously it does not fit either of the two criteria: prime detection and transposable.)

Smallest size wins.

You can use any language, and any library function except if the sole purpose of that function is to find, generate, or detect primes.

Edit:

While the winner would probably be the Golfscript solution, I'll award a 50 point bounty for the best C or C++ solution!

答:
GolfScript, 13 × 1

```<code>~.,2>{1$\%!}?
</code>```

GolfScript strikes again!

Repeats the input if it is prime, otherwise prints the input concatenated with its smallest proper divisor.  Yes, I know that's stretching the definition of "anything what unambiguously identifies the result", but doing anything fancier would cost a few extra characters.  If you want nicer output, appending the three characters ;]! to the code yields 1 for primes and 0 for composite numbers.

The algorithm is really inefficient, just brute force trial division from 2 to n−1.
Most GolfScript operators are only single characters, so this code works just as well transposed.  Annoyingly, though, the assignment operator : doesn't allow whitespace between itself and its target, so I had to do this entirely without variables.

Title: Transposed, primes, oh my!

Body:
GolfScript, 13 × 1

~.,2>{1$\%!}?

GolfScript strikes again!

Repeats the input if it is prime, otherwise prints the input concatenated with its smallest proper divisor.  Yes, I know that's stretching the definition of "anything what unambiguously identifies the result", but doing anything fancier would cost a few extra characters.  If you want nicer output, appending the three characters ;]! to the code yields 1 for primes and 0 for composite numbers.

The algorithm is really inefficient, just brute force trial division from 2 to n−1.
Most GolfScript operators are only single characters, so this code works just as well transposed.  Annoyingly, though, the assignment operator : doesn't allow whitespace between itself and its target, so I had to do this entirely without variables.


答:
Befunge-93, 12 bytes

```<code>1::.9`#@_1+#
</code>```

Explanation:

```<code>1             Start stack with the number 1
  :.          Print the number on top of the stack
 :  9`        Set (number on top of the stack) > 9
      #       Skip the next character, which would otherwise stop the program
        _     Is the number in the top of the stack true (i.e. not 0)?
       @      If yes, stop the program
         1+   If no, add 1 to the top of the stack
           #  Skip the next character. Since we're at the edge of the program,
              it would wrap to the beginning, so the character being skipped is
              the "1" at the left edge. That is, "don't put 1 on the stack again"
</code>```

Title: Print numbers from 1 to 10

Body:
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

This is code-golf, so shortest answer in bytes wins!

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Befunge-93, 12 bytes

1::.9`#@_1+#

Explanation:

1             Start stack with the number 1
  :.          Print the number on top of the stack
 :  9`        Set (number on top of the stack) > 9
      #       Skip the next character, which would otherwise stop the program
        _     Is the number in the top of the stack true (i.e. not 0)?
       @      If yes, stop the program
         1+   If no, add 1 to the top of the stack
           #  Skip the next character. Since we're at the edge of the program,
              it would wrap to the beginning, so the character being skipped is
              the "1" at the left edge. That is, "don't put 1 on the stack again"


答:
BrainFuck, 55 Bytes

```<code>+++++++++>-->-[-----<+>]+++++++++[-<.+<.>>]<<[->-<]>.-.
</code>```

Output:

```<code>1   2   3   4   5   6   7   8   9   10
</code>```

(Indents as seperators)

Try it here:

https://fatiherikli.github.io/brainfuck-visualizer/#KysrKysrKysrPi0tPi1bLS0tLS08Kz5dKysrKysrKysrWy08Lis8Lj4+XTw8Wy0+LTxdPi4tLg==

Title: Print numbers from 1 to 10

Body:
BrainFuck, 55 Bytes

+++++++++>-->-[-----<+>]+++++++++[-<.+<.>>]<<[->-<]>.-.

Output:

1   2   3   4   5   6   7   8   9   10

(Indents as seperators)

Try it here:

https://fatiherikli.github.io/brainfuck-visualizer/#KysrKysrKysrPi0tPi1bLS0tLS08Kz5dKysrKysrKysrWy08Lis8Lj4+XTw8Wy0+LTxdPi4tLg==


答:
Ruby, 24 bytes

```<code>eval(gets.tr'ab','[]')*1
</code>```

(This is just xnor's brilliant idea in Ruby form. My other answer is a solution I actually came up with myself.)

The program takes the input, transforms a and b to [ and ] respectively, and evaluates it.

Valid input will form a nested array, and nothing happens. An unbalanced expression will make the program crash. In Ruby empty input is evaluated as nil, which will crash because nil has not defined a * method.

Title: Count of "a"s and "b"s must be equal. Did you get it computer?

Body:
In the popular (and essential) computer science book, An Introduction to Formal Languages and Automata by Peter Linz, the following formal language is frequently stated:

$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$

mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".

Challenge

Write a working program/function which gets a string, containing "a"s and "b"s only, as input and returns/outputs a truth value, saying if this string is valid the formal language L.

Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.

Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. More info here.

Standard code golf rules apply.

This is a code-golf. Shortest code in bytes wins. Good luck!

Truthy test cases

```<code>"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
</code>```

Falsy test cases

```<code>""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
</code>```

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 85994; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 48934; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Ruby, 24 bytes

eval(gets.tr'ab','[]')*1

(This is just xnor's brilliant idea in Ruby form. My other answer is a solution I actually came up with myself.)

The program takes the input, transforms a and b to [ and ] respectively, and evaluates it.

Valid input will form a nested array, and nothing happens. An unbalanced expression will make the program crash. In Ruby empty input is evaluated as nil, which will crash because nil has not defined a * method.


答:
C, 60 Bytes

```<code>#include <stdio.h>
main(){int a,b;scanf("%d %d",&a,&b);a%b==0;}
</code>```

Title: Divisibility test

Body:
Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 3 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
C, 60 Bytes

#include <stdio.h>
main(){int a,b;scanf("%d %d",&a,&b);a%b==0;}


答:
LOLCODE, 79 bytes

```<code>IM IN YR l UPPIN YR v TIL BOTH SAEM v AN 10
VISIBLE SUM OF v AN 1
IM OUTTA YR l
</code>```

This code may need some tweaking depending on the compiler you're using. Some want you to add HAI/KTHXBYE, some want you to declare the variable ahead of time. One compiler breaks if your loop name is shorter than two characters, even though the loop name is never used.

Title: Print numbers from 1 to 10

Body:
LOLCODE, 79 bytes

IM IN YR l UPPIN YR v TIL BOTH SAEM v AN 10
VISIBLE SUM OF v AN 1
IM OUTTA YR l

This code may need some tweaking depending on the compiler you're using. Some want you to add HAI/KTHXBYE, some want you to declare the variable ahead of time. One compiler breaks if your loop name is shorter than two characters, even though the loop name is never used.


答:
Excel 6 bytes

=ROW(

Select the cells A1:A10, type the above (once only) and ctrl-shift-enter as an array formula (which links the cells in an array, with one common formula).

Note the total lack of numerals entered in this process. :-)

Title: Print numbers from 1 to 10


答:
Befunge, 6 bytes

```<code>&&%!.@
</code>```

Try it here! Input two numbers, separated by a space. Output is 0 or 1 for falsy or truthy.

Title: Divisibility test

Body:
Befunge, 6 bytes

&&%!.@

Try it here! Input two numbers, separated by a space. Output is 0 or 1 for falsy or truthy.


答:
Mathematica - 17 13 3 bytes

```<code>∣
</code>```

Thanks to @MartinEnder for saving a ton of bytes!

Title: Divisibility test

Body:
Mathematica - 17 13 3 bytes

∣

Thanks to @MartinEnder for saving a ton of bytes!


答:
Excel, <s>31</s> 13 bytes

```<code>=0=MOD(A1,A2)
</code>```

Enter n in A1, d in A2.

For some reason I convinced myself that we had to handle all integers, so I had =IFERROR(A1/A2=INT(A1/A2),A1=0) to handle d=0.

Title: Divisibility test

Body:
Excel, <s>31</s> 13 bytes

=0=MOD(A1,A2)

Enter n in A1, d in A2.

For some reason I convinced myself that we had to handle all integers, so I had =IFERROR(A1/A2=INT(A1/A2),A1=0) to handle d=0.


答:
Racket, 91 bytes

```<code>(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr x)))(/(length x)2)))
</code>```

Expects input in the form of a list of characters.  If you really need to put it in as a raw string, that adds 21 extra characters (for 112 bytes):

```<code>(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr(string->list x))))(/(string-length x)2)))
</code>```

An even longer (102 bytes with list input) way, but I think it's creative so I'm leaving it here:

```<code>(λ(x)(and(eqv?(/(length x)2)(length(member #\b x)))(eqv?(length(remove-duplicates(member #\b x)))1)))
</code>```

Explanation to follow.

Body:
Racket, 91 bytes

(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr x)))(/(length x)2)))

Expects input in the form of a list of characters.  If you really need to put it in as a raw string, that adds 21 extra characters (for 112 bytes):

(λ(x)((λ(y)(equal?(append(make-list(- 1 y)#\a)(make-list y #\b))(cdr(string->list x))))(/(string-length x)2)))

An even longer (102 bytes with list input) way, but I think it's creative so I'm leaving it here:

(λ(x)(and(eqv?(/(length x)2)(length(member #\b x)))(eqv?(length(remove-duplicates(member #\b x)))1)))

Explanation to follow.


问:
Dice from Changing Random Generator

Introduction

You are given a random integer generator with the following implementation

The first invocation always returns 1.

The second invocation returns a random integer between 1 and 2.

The third invocation returns a random integer between 1 and 3.

The nth invocation returns a random integer between 1 and n, inclusive.

Based on the above function, write a random dice generator that is perfectly random, returning a value between 1 and 6 (inclusive) with equal probability.

Rules

Your program/function should result in a random integer between 1 and 6, inclusive, in some usable form, i.e., to standard output or as a function return value.

The ascending random number generator above can be defined as a "free" function in your program (i.e., doesn't count toward your character count), or a separate script/program that is executed as needed, assuming the state (n) is persistent between calls.

Assume that no more than 1000 dice rolls will ever be requested in a single use case of your program, and the initial random number generator can be reset to 1 at the end of 1000 dice rolls to avoid overflow of n.

Your program may not use any other source of random numbers except the ascending random generator defined above.  You may of course request multiple random numbers from the random number generator for each single dice roll output.

This is code-golf, so winner is shortest answer or most votes in the event of a tie.  If you can generate 1000 dice rolls using less than 1000 generated random numbers, give yourself a 10-point efficiency bonus.

Example

```<code>./asc-rand
1 # random integer between 1 and 1
./asc-rand
1 # random integer between 1 and 2
./asc-rand
3 # random integer between 1 and 3
./asc-rand
4 # random integer between 1 and 4

# dice-gen generates random dice based on output of asc-rand program.
./dice-gen
3
./dice-gen
6
./dice-gen
5
./dice-gen
1
</code>```

答:
Perl, 22 or 45

Implementation of the ascending random number generator:

```<code>my $n=0;
sub r { $n++; return 1+int(rand$n); }
</code>```

Generating:

```<code>#copy of the Scala solution; short code; uses 6N rolls
sub s{r;r;r;r;r;1+r%6}
#more efficient implementation, uses approximately 6+N+lnN rolls
sub roll { do{$a=r-1}while($a>$n-$n%6);return 1+(1+$a)%6 }
</code>```

Testing out:

```
n number   chisquare
1 10001867 0.348569
2 10004853 2.355161
3 9994395  3.141602
4 10000177 0.003133
5 9999227  0.059753
6 9999481  0.026936
T 60000000 5.935154
60000000 dice rolls took 60000042 calls to r and 570.432735 seconds
```

Title: Dice from Changing Random Generator

Body:
Perl, 22 or 45

Implementation of the ascending random number generator:

my $n=0;
sub r { $n++; return 1+int(rand$n); }

Generating:

#copy of the Scala solution; short code; uses 6N rolls
sub s{r;r;r;r;r;1+r%6}
#more efficient implementation, uses approximately 6+N+lnN rolls
sub roll { do{$a=r-1}while($a>$n-$n%6);return 1+(1+$a)%6 }

Testing out:

n number   chisquare
1 10001867 0.348569
2 10004853 2.355161
3 9994395  3.141602
4 10000177 0.003133
5 9999227  0.059753
6 9999481  0.026936
T 60000000 5.935154
60000000 dice rolls took 60000042 calls to r and 570.432735 seconds


答:
C#, <s>27</s> <s>13</s> 12 Bytes

```<code>a=>b=>a%b<1;
</code>```

Thanks to TuukkaX for pointing out anonymous lambdas are acceptable.
Thanks to David Conrad for pointing me on to currying which I wasn't even aware was a thing.

Short and sweet, since we're only dealing with integers we can use <1 rather than ==0 and save a whole byte.

Title: Divisibility test

Body:
C#, <s>27</s> <s>13</s> 12 Bytes

a=>b=>a%b<1;

Thanks to TuukkaX for pointing out anonymous lambdas are acceptable.
Thanks to David Conrad for pointing me on to currying which I wasn't even aware was a thing.

Short and sweet, since we're only dealing with integers we can use <1 rather than ==0 and save a whole byte.


Title: Print numbers from 1 to 10

Body:
Maple, 10 bytes

seq(1..10)

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10


答:
F# 17 bytes

Equal to Haskell !! yuppee.

```<code>printf"%A"[1..10]
</code>```

Output:

```<code>[1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
</code>```

For each number on a separate line, 28 bytes:

```<code>Seq.iter(printfn"%d")[1..10]
</code>```

If you remove the standard output permission, simply [1..10] prints out the numbers in F# interactive.

```<code>[1..10];;
> val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
</code>```

Title: Print numbers from 1 to 10

Body:
F# 17 bytes

Equal to Haskell !! yuppee.

printf"%A"[1..10]

Output:

[1; 2; 3; 4; 5; 6; 7; 8; 9; 10]

For each number on a separate line, 28 bytes:

Seq.iter(printfn"%d")[1..10]

If you remove the standard output permission, simply [1..10] prints out the numbers in F# interactive.

[1..10];;
> val it : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]


问:
Theoretically output Graham's number
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

var QUESTION_ID=83873,OVERRIDE_USER=48934;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:\.\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
F#, <s>111</s> 108 bytes

Edit

This is using the function below to calulcate Graham's number

```<code>let rec u=function|b,1->int<|3I**b|1,c->3|b,c->u(u(b-1,c),c-1)
and g=function|1->u(3.,4.)|a->u(3.,g (a-1))
g 63
</code>```

Here's my previous answer which, well, didnt:

Pretty straightforward. Just a definition of the u function.

```<code>let rec u=function|a,b,1->a**b|a,1.,c->a|a,b,c->u(a,u(a,b-1.,c),c-1)
</code>```

Usage:

```<code>u(3.,3.,2)
val it : float = 7.625597485e+12
</code>```

If I assumed 3 as the value for a, I could cut it to 60:

```<code>let rec u=function|b,1->3.**b|1.,c->3.|b,c->u(u(b-1.,c),c-1)
</code>```

Usage:

```<code>u(3.,2)
val it : float = 7.625597485e+12
</code>```

Title: Theoretically output Graham's number

Body:
F#, <s>111</s> 108 bytes

Edit

This is using the function below to calulcate Graham's number

let rec u=function|b,1->int<|3I**b|1,c->3|b,c->u(u(b-1,c),c-1)
and g=function|1->u(3.,4.)|a->u(3.,g (a-1))
g 63

Here's my previous answer which, well, didnt:

Pretty straightforward. Just a definition of the u function.

let rec u=function|a,b,1->a**b|a,1.,c->a|a,b,c->u(a,u(a,b-1.,c),c-1)

Usage:

u(3.,3.,2)
val it : float = 7.625597485e+12

If I assumed 3 as the value for a, I could cut it to 60:

let rec u=function|b,1->3.**b|1.,c->3.|b,c->u(u(b-1.,c),c-1)

Usage:

u(3.,2)
val it : float = 7.625597485e+12


问:
Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github

答:
Shorter way to define an empty numeric array, if the stack is empty

To push an empty numeric array you normally use []. However, if the stack is empty you can save a byte using v. This function by default concatenates all stack contents vertically, so if the stack is empty it produces the empty array.

You can see it in action for example here.

Title: Tips for golfing in MATL


答:
F#, 18 bytes

```<code>let d a=(%)a>>(=)0
</code>```

Usage:

```<code>d 6 3;;
> val it : bool = true
</code>```

I can shave 1 byte if I define a lambda instead but then I can't use it later.

```<code>fun a->(%)a>>(=)0
</code>```

Title: Divisibility test

Body:
F#, 18 bytes

let d a=(%)a>>(=)0

Usage:

d 6 3;;
> val it : bool = true

I can shave 1 byte if I define a lambda instead but then I can't use it later.

fun a->(%)a>>(=)0


问:
Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Title: Can you Golf Golf?

Body:
Perl, 74

{@c=map{3+int rand 3}(0)x18;$s=0;$s+=$_ for@c;redo unless$s==72}print"@c"

Alternative solution:

@q=((3,5)x($a=int rand 9),(4,4)x(9-$a));%t=map{(rand,$_)}(0..17);print"@q[@t{sort keys%t}]"


问:
Substring Sum Set

Introduction

Let's observe this array: [3, 2, 4, 1, 1, 5, 1, 2].

Each element displays the length of the substring which must be summed up. Let's take a look at the first element of the above array:

```<code>[3, 2, 4, 1, 1, 5, 1, 2]
 ^
</code>```

The element at the first index is 3, so we now take a substring of length three with the same index as the starting position:

```<code>[3, 2, 4]
</code>```

When summed up, this results into 9, so the first element of the substring sum set is 9.

We do this for all the elements in the array:

```<code>3 -> [3, 2, 4]
2 -> [2, 4]
4 -> [4, 1, 1, 5]
1 -> [1]
1 -> [1]
5 -> [5, 1, 2]
1 -> [1]
2 -> [2]
</code>```

You can see that the number 5 is a bit of a weird case. That number exceeds the length of the array:

```<code>[3, 2, 4, 1, 1, 5, 1, 2]
                ^  ^  ^  ^  ^
</code>```

We'll ignore everything that exceeds the array, so we just use [5, 1, 2].

The last step is to sum everything up:

```<code>[3, 2, 4]     -> 9
[2, 4]        -> 6
[4, 1, 1, 5]  -> 11
[1]           -> 1
[1]           -> 1
[5, 1, 2]     -> 8
[1]           -> 1
[2]           -> 2
</code>```

And that is the array that needs to be outputted:

```<code>[9, 6, 11, 1, 1, 8, 1, 2]
</code>```

The Task

Given an non-empty array with positive (non-zero) integers, output the substring sum set. This is code-golf, so the submission with the smallest number of bytes wins!

Test cases

```<code>[1, 2, 3, 4, 5] -> [1, 5, 12, 9, 5]
[3, 3, 3, 3, 3, 3, 3, 3] -> [9, 9, 9, 9, 9, 9, 6, 3]
[5, 1, 2, 4, 1] -> [13, 1, 6, 5, 1]
[1] -> [1]
</code>```

答:
Python 3, 47 bytes

```<code>lambda X:[sum(X[i:i+k])for i,k in enumerate(X)]
</code>```

Pretty straightforward implementation. Python's default behavior for slices that go past the end of the list was very convenient here.

Title: Substring Sum Set

Body:
Python 3, 47 bytes

lambda X:[sum(X[i:i+k])for i,k in enumerate(X)]

Pretty straightforward implementation. Python's default behavior for slices that go past the end of the list was very convenient here.


答:
MATL, <s>17</s> <s>14</s> 13 bytes

```<code>fGy+!-R0<G*!s
</code>```

Explanation

Try it online! Or verify all test cases (code modified to handle several inputs).

```<code>f     % Take input implicitly. Indices of nonzero elements: this gives [1 2 ... n]
      % where n is input size
G     % Push input again
y     % Push a copy of [1 2 ... n]
+     % Add. Gives [a+1 b+2...] where [a b...] is the input
!     % Transpose into a column vector
-     % Subtraction with broadcast. Gives 2D array
R     % Keep upper triangular part, making the rest of entries 0
0<    % True for negative entries. Each row corresponds to a substring sum.
      % For each row, this gives true for the entries of the input that make up
      % that substring sum. Each row is thus a mask to select entries of the input
G     % Push input again
*     % Multiply with broadcast. This multiplies the input times each row
!s    % Sum of each row. Implicitly display
</code>```

Title: Substring Sum Set

Body:
Introduction

Let's observe this array: [3, 2, 4, 1, 1, 5, 1, 2].

Each element displays the length of the substring which must be summed up. Let's take a look at the first element of the above array:

```<code>[3, 2, 4, 1, 1, 5, 1, 2]
 ^
</code>```

The element at the first index is 3, so we now take a substring of length three with the same index as the starting position:

```<code>[3, 2, 4]
</code>```

When summed up, this results into 9, so the first element of the substring sum set is 9.

We do this for all the elements in the array:

```<code>3 -> [3, 2, 4]
2 -> [2, 4]
4 -> [4, 1, 1, 5]
1 -> [1]
1 -> [1]
5 -> [5, 1, 2]
1 -> [1]
2 -> [2]
</code>```

You can see that the number 5 is a bit of a weird case. That number exceeds the length of the array:

```<code>[3, 2, 4, 1, 1, 5, 1, 2]
                ^  ^  ^  ^  ^
</code>```

We'll ignore everything that exceeds the array, so we just use [5, 1, 2].

The last step is to sum everything up:

```<code>[3, 2, 4]     -> 9
[2, 4]        -> 6
[4, 1, 1, 5]  -> 11
[1]           -> 1
[1]           -> 1
[5, 1, 2]     -> 8
[1]           -> 1
[2]           -> 2
</code>```

And that is the array that needs to be outputted:

```<code>[9, 6, 11, 1, 1, 8, 1, 2]
</code>```

The Task

Given an non-empty array with positive (non-zero) integers, output the substring sum set. This is code-golf, so the submission with the smallest number of bytes wins!

Test cases

```<code>[1, 2, 3, 4, 5] -> [1, 5, 12, 9, 5]
[3, 3, 3, 3, 3, 3, 3, 3] -> [9, 9, 9, 9, 9, 9, 6, 3]
[5, 1, 2, 4, 1] -> [13, 1, 6, 5, 1]
[1] -> [1]
</code>```

Body:
MATL, <s>17</s> <s>14</s> 13 bytes

fGy+!-R0<G*!s

Explanation

Try it online! Or verify all test cases (code modified to handle several inputs).

f     % Take input implicitly. Indices of nonzero elements: this gives [1 2 ... n]
      % where n is input size
G     % Push input again
y     % Push a copy of [1 2 ... n]
+     % Add. Gives [a+1 b+2...] where [a b...] is the input
!     % Transpose into a column vector
-     % Subtraction with broadcast. Gives 2D array
R     % Keep upper triangular part, making the rest of entries 0
0<    % True for negative entries. Each row corresponds to a substring sum.
      % For each row, this gives true for the entries of the input that make up
      % that substring sum. Each row is thus a mask to select entries of the input
G     % Push input again
*     % Multiply with broadcast. This multiplies the input times each row
!s    % Sum of each row. Implicitly display


答:
Python, 40 bytes

f=lambda x:x and[sum(x[:x[0]])]+f(x[1:])
```

Test it on Ideone.

Title: Substring Sum Set

Body:
Python, 40 bytes

f=lambda x:x and[sum(x[:x[0]])]+f(x[1:])

Test it on Ideone.


答:
Javascript (using External Library) (66 bytes)

```<code>n=>_.From(n).Select((v,i)=>_.From(n).Slice(i,i+v).Sum()).ToArray()
</code>```

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: _.From is loading the input array into the library, which is basically LINQ for js. Then each item in the array is mapped according to the following predicate: Take the input, and slice it from current item index and take that index plus the current item's value. Then Sum up that subsequence. Convert the result to a native JS array and return it

Title: Substring Sum Set

Body:
Javascript (using External Library) (66 bytes)

n=>_.From(n).Select((v,i)=>_.From(n).Slice(i,i+v).Sum()).ToArray()

Link to lib: https://github.com/mvegh1/Enumerable

Code explanation: _.From is loading the input array into the library, which is basically LINQ for js. Then each item in the array is mapped according to the following predicate: Take the input, and slice it from current item index and take that index plus the current item's value. Then Sum up that subsequence. Convert the result to a native JS array and return it


答:
JavaScript ES6, 50 bytes

a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))
```

<p>Pretty self-explanatory. It <code>map</code>s over each element in the array, getting the <code>slice</code> from that <code>i</code>ndex through the index plus that <code>e</code>lement's value, and <code>reduce</code>ing by adding.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=
  a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

;[
  [3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]
].forEach(function(test){
  document.getElementById('p').textContent += test + ' => ' + f(test) + '\n';
});</code>```

```</code>```

Title: Substring Sum Set

Body:
JavaScript ES6, 50 bytes

a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

Pretty self-explanatory. It maps over each element in the array, getting the slice from that index through the index plus that element's value, and reduceing by adding.

f=
  a=>a.map((e,i)=>a.slice(i,i+e).reduce((a,b)=>a+b))

;[
  [3, 2, 4, 1, 1, 5, 1, 2],
  [1, 2, 3, 4, 5],
  [3, 3, 3, 3, 3, 3, 3, 3,],
  [5, 1, 2, 4, 1],
  [1]
].forEach(function(test){
  document.getElementById('p').textContent += test + ' => ' + f(test) + '\n';
});

<pre id="p"></pre>


答:
Pyth, 8 bytes

```<code>.es:Qk+b
</code>```

Test suite.

Translation of El's answer in Python.

Title: Substring Sum Set

Body:
Pyth, 8 bytes

.es:Qk+b

Test suite.

Translation of El's answer in Python.


问:
METAscii Code Golf
Introduction

Here at code colf SE, we appear to love meta-problems. Here, I've tried to compose a meta-problem that's an interesting, not-straightforward challenge.

Challenge

The answer code is allowed to read its own source code, but not allowed to use external resources.

All characters should be 5-lines tall. Characters used in the ascii representation are also not important, though they must be visible. Each visible character in the output will count as one byte, regardless of cheaty byte-values. Spaces used in the code are necessary, and may be only one byte wide if desired.

Lowest Byte Count of the output wins. Output must exist and include at least 1 visible byte.

Example Input and Output

Input:

For an example code:

```<code>print theanswer
</code>```

One possible answer is:

Output:

```<code>PPPP  RRRR  III N   N TTTTTT  TTTTTT H  H EEEE   AA  N   N  SSS  W     W EEEE RRRR
P   P R   R  I  NN  N   TT      TT   H  H E     A  A NN  N S     W     W E    R   R
PPPP  RRRR   I  N N N   TT      TT   HHHH EEE   AAAA N N N  SSS  W  W  W EEE  RRRR
P     R R    I  N  NN   TT      TT   H  H E     A  A N  NN     S  W W W  E    R R
P     R  RR III N   N   TT      TT   H  H EEEE  A  A N   N SSSS    W W   EEEE R  RR
</code>```

The alphabet used should consist of the following patterns, the characters used are not important:
:

```<code> AA  BBBB   CCC DDD  EEEE FFFF  GGG  H  H III     J K  K L    M   M N   N  OOO  PPPP   QQQ   RRRR   SSS  TTTTTT U   U V     V W     W X   X Y   Y ZZZZZ
A  A B   B C    D  D E    F    G     H  H  I      J K K  L    MM MM NN  N O   O P   P Q   Q  R   R S       TT   U   U V     V W     W  X X   Y Y     Z
AAAA BBBB  C    D  D EEE  FFF  G  GG HHHH  I      J KK   L    M M M N N N O   O PPPP  Q   Q  RRRR   SSS    TT   U   U  V   V  W  W  W   X     Y     Z
A  A B   B C    D  D E    F    G   G H  H  I  J   J K K  L    M   M N  NN O   O P     Q  Q   R R       S   TT   U   U   V V    W W W   X X    Y    Z
A  A BBBB   CCC DDD  EEEE F     GGG  H  H III  JJJ  K  K LLLL M   M N   N  OOO  P      QQ Q  R  RR SSSS    TT    UUU     V      W W   X   X   Y   ZZZZZ

 11   22  333  4  4 5555   6   77777  888   9999  000       //!!!  @@@   # #  %   %%  ^^   &&    ((  ))
111  2  2    3 4  4 5     6       7  8   8 9   9 0  00     // !!! @   @ #####    %%  ^  ^ &  &  ((    ))
 11    2   33  4444 555  6666    7    888   9999 0 0 0    //  !!! @  @@  # #    %%         &&& &((    ))
 11   2      3    4    5 6   6   7   8   8    9  00  0   //       @     #####  %%         & & & ((    ))
11l1 2222 333     4 555   666    7    888    9    000   //    !!!  @@@   # #  %%   %       &&&&  ((  ))   ____
</code>```

For other characters, the equivalent produced by this generator using the 'Alphabet' font will be acceptable.   If the output generated by the tool is more than 5 characters tall, use the central 5 characters for output.

Edit - I've allowed the program to read its own source code to possibly open this question up to interesting answers.

Title: METAscii Code Golf

Body:
Python 2, 2142 bytes

Should work, it's pretty confusing to read the output.

n=["","","","",""]
t=["EEEE","E  E","EEE ","E   "," EE "," E "," EEE ","E   E","E    ","  EE  ","EEEE "," EEEE","   ","EEE","     ","EE EE","    "]
e=[[t[4],t[1],t[0],t[1],t[1]],[t[2],t[1],t[1],t[1],t[2]],[t[0],t[3],t[2],t[3],t[0]],[t[0],t[3],t[2],t[3],t[3]],[t[6],t[8],"E  EE",t[7],t[6]],["EEE",t[5],t[5],t[5],"EEE"],[t[3],t[3],t[3],t[3],t[0]],[t[7],"EE  E","E E E","E  EE",t[7]],[t[6],t[7],t[7],t[7],t[6]],[t[10],t[7],t[10],t[8],t[8]],[t[10],t[7],t[10],"E E  ","E  EE"],[t[6],"E    ",t[6],"    E",t[6]],["E"*6,t[9],t[9],t[9],t[9]],[t[4],t[2],t[4],t[4],t[0]],[t[4],t[1],"  E "," E  ",t[0]],[t[2],"   E",t[4],"   E",t[2]],[t[1],t[1],t[0],"   E","   E"],[t[0],t[3],t[2],"   E",t[2]],["  E  "," E   ",t[10],t[7],t[6]],["EEEEE","   E ","  E  ","  E  ","  E  "],[t[6],t[7],t[6],t[7],t[6]],[t[11],t[7],t[11],"   E ","  E  "],[t[6],"E  EE","E E E","EE  E",t[6]],["EE    "," EE   ","  EE  ","   EE ","    EE"],[t[12],t[13],t[12],t[13],t[12]],[t[0],"EE  ","EE  ","EE  ",t[0]],[t[0],"  EE","  EE","  EE",t[0]],[t[15],t[15],t[14],t[14],t[14]],["  ","  ","  ","  ","EE"],[" EE","EE ","EE ","EE "," EE"],["EE "," EE"," EE"," EE","EE "],[t[12],t[5],t[13],t[5],t[12]],[t[16],t[16],t[16],t[16],t[0]],["  ","EE","  ","EE","  "],["  ","EE","  ","EE"," E"]]
def s(i):
 if i==" ":r()
 if i=="a":g(e[0])
 if i=="d":g(e[1])
 if i=="e"or i=="E":g(e[2])
 if i=="f":g(e[3])
 if i=="g":g(e[4])
 if i=="i":g(e[5])
 if i=="l":g(e[6])
 if i=="n":g(e[7])
 if i=="o":g(e[8])
 if i=="p":g(e[9])
 if i=="r":g(e[10])
 if i=="s":g(e[11])
 if i=="t":g(e[12])
 if i=="1":g(e[13])
 if i=="2":g(e[14])
 if i=="3":g(e[15])
 if i=="4":g(e[16])
 if i=="5":g(e[17])
 if i=="6":g(e[18])
 if i=="7":g(e[19])
 if i=="8":g(e[20])
 if i=="9":g(e[21])
 if i=="0":g(e[22])
 if i=="\\":g(e[23])
 if i=="=":g(e[24])
 if i=="[":g(e[25])
 if i=="]":g(e[26])
 if i=="\"":g(e[27])
 if i==",":g(e[28])
 if i=="(":g(e[29])
 if i==")":g(e[30])
 if i=="+":g(e[31])
 if i=="_":g(e[32])
 if i==":":g(e[33])
 if i==";":g(e[34])
 r()
def g(p):
 for i in range(5):n[i]+=p[i]
def r():g([" "," "," "," "," "])
for l in open(__file__).read().split("\n"):
 for i in l:s(i)
 print"\n".join(n);n=["","","","",""]

Output is 47965 bytes.

Can probably be golfed a lot more.

The code above uses half of the alphabet, all numbers and some symbols/special characters. I used the letter E for the output.

The characters are a list of five strings, each for one line. Also, to save a few bytes, there's a list with common lines ("EEEE", "E  E", etc.)

The , has two lines, and one of them is below most characters, so I only included the upper one (same for underscore).


答:
F#, <s>84</s> 82 bytes

```<code>let f(A:int[])=[for i in 0..A.Length-1->Seq.skip i A|>Seq.truncate A.[i]|>Seq.sum]
</code>```

Title: Substring Sum Set

Body:
F#, <s>84</s> 82 bytes

let f(A:int[])=[for i in 0..A.Length-1->Seq.skip i A|>Seq.truncate A.[i]|>Seq.sum]


答:
Excel, 21 bytes

=SUM(OFFSET(A1,,,A1))

Open a new spreadsheet, put the test values in column A. Enter the formula in B1 and double click the cell handle to ride the range.

Title: Substring Sum Set


问:
Solve the eight queens problem at compile-time
Can you solve the eight queens puzzle at compile-time?

Pick any suitable output format.

I'm particularly interested in a C++ template metaprogramming solution, but you can use languages that have similar constructs, like, for example, Haskell's type system.

Ideally your metaprogram would output all solutions. No hardcoding.

答:
Here's a C++11 solution without any templates:

```<code>constexpr int trypos(
    int work, int col, int row, int rows, int diags1, int diags2,
    int rowbit, int diag1bit, int diag2bit);

constexpr int place(
    int result, int work, int col, int row, int rows, int diags1, int diags2)
{
    return result != 0 ? result
        : col == 8 ? work
        : row == 8 ? 0
        : trypos(work, col, row, rows, diags1, diags2,
                 1 << row, 1 << (7 + col - row), 1 << (14 - col - row));
}

constexpr int trypos(
    int work, int col, int row, int rows, int diags1, int diags2,
    int rowbit, int diag1bit, int diag2bit)
{
    return !(rows & rowbit) && !(diags1 & diag1bit) && !(diags2 & diag2bit)
        ? place(
            place(0, work*10 + 8-row, col + 1, 0,
                  rows | rowbit, diags1 | diag1bit, diags2 | diag2bit),
            work, col, row + 1, rows, diags1, diags2)
        : place(0, work, col, row + 1, rows, diags1, diags2);
}

int places = place(0, 0, 0, 0, 0, 0, 0);
</code>```

The solution is encoded as decimal digits, as in FredOverflow's answers.  GCC 4.7.1 compiles the above file into the following assembly source with g++ -S -std=c++11 8q.cpp:

```<code>    .file   "8q.cpp"
    .globl  places
    .data
    .align 4
    .type   places, @object
    .size   places, 4
places:
    .long   84136275
    .ident  "GCC: (GNU) 4.7.1"
    .section    .note.GNU-stack,"",@progbits
</code>```

The value of the symbol places is 84136275, i.e. the first queen is at a8, the second at b4 etc.

Body:
Here's a C++11 solution without any templates:

constexpr int trypos(
    int work, int col, int row, int rows, int diags1, int diags2,
    int rowbit, int diag1bit, int diag2bit);

constexpr int place(
    int result, int work, int col, int row, int rows, int diags1, int diags2)
{
    return result != 0 ? result
        : col == 8 ? work
        : row == 8 ? 0
        : trypos(work, col, row, rows, diags1, diags2,
                 1 << row, 1 << (7 + col - row), 1 << (14 - col - row));
}

constexpr int trypos(
    int work, int col, int row, int rows, int diags1, int diags2,
    int rowbit, int diag1bit, int diag2bit)
{
    return !(rows & rowbit) && !(diags1 & diag1bit) && !(diags2 & diag2bit)
        ? place(
            place(0, work*10 + 8-row, col + 1, 0,
                  rows | rowbit, diags1 | diag1bit, diags2 | diag2bit),
            work, col, row + 1, rows, diags1, diags2)
        : place(0, work, col, row + 1, rows, diags1, diags2);
}

int places = place(0, 0, 0, 0, 0, 0, 0);

The solution is encoded as decimal digits, as in FredOverflow's answers.  GCC 4.7.1 compiles the above file into the following assembly source with g++ -S -std=c++11 8q.cpp:

    .file   "8q.cpp"
    .globl  places
    .data
    .align 4
    .type   places, @object
    .size   places, 4
places:
    .long   84136275
    .ident  "GCC: (GNU) 4.7.1"
    .section    .note.GNU-stack,"",@progbits

The value of the symbol places is 84136275, i.e. the first queen is at a8, the second at b4 etc.


答:
C++, 36 bytes

bool d(int n, int d){return n%d==0;}

Explanation:

```<code>bool isDivisible(int dividend, int divisor) {
    return n % d == 0; // the modulo operator returns remainder,
    // if the number evenly divides, there will be no remainder
}
</code>```

Usage:

```<code>#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
    int div = std::stoi(argv[1]);
    int divis = std::stoi(argv[2]);
    if (isDivisible(div, divis)) {
        std::cout << "They're evenly divisible!" << std::endl;
    } else {
        std::cout << "They're not evenly divisible." << std::endl;
    }
    return 0;
}
</code>```

Title: Divisibility test

Body:
Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 3 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
C++, 36 bytes

bool d(int n, int d){return n%d==0;}

Explanation:

bool isDivisible(int dividend, int divisor) {
    return n % d == 0; // the modulo operator returns remainder,
    // if the number evenly divides, there will be no remainder
}

Usage:

#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
    int div = std::stoi(argv[1]);
    int divis = std::stoi(argv[2]);
    if (isDivisible(div, divis)) {
        std::cout << "They're evenly divisible!" << std::endl;
    } else {
        std::cout << "They're not evenly divisible." << std::endl;
    }
    return 0;
}


答:
Haskell, <s>34</s>, 33 bytes

```<code>f l@(x:y)=sum(take x l):f y
f x=x
</code>```

One byte saved by nimi.

Title: Substring Sum Set

Body:
Haskell, <s>34</s>, 33 bytes

f l@(x:y)=sum(take x l):f y
f x=x

One byte saved by nimi.


答:
Hexagony, <s>15, 13, 12</s> 10 bytes

Everybody's favorite hexagon-based language! :D

TL;DR works using magic, unformatted solutions in decreasing byte count:

```<code>?{?..>1'%<.@!'/
?{?!1\.'%<@.>
?{?\!1@'%\!(
?{?!1\@'%<
</code>```

Saved 2 bytes thanks to @MartinEnder's layout wizardry.

@FryAmTheEggman saved 1 byte by using the corners more creatively

Both @MartinEnder and @FryAmTheEggman came up with a 10 byte solution that doesn't print anything for falsely values.

My solution (15):

Unformatted:

```<code>?{?..>1'%<.@!'/
</code>```

Formatted:

```<code>  ? { ?
 . . > 1
' % < . @
 ! ' / .
  . . .
</code>```

@Martin Ender's Solution (13):

Unformatted:

```<code>?{?!1\.'%<@.>
</code>```

Formatted:

```<code>  ? { ?
 ! 1 \ .
' % < @ .
 > . . .
  . . .
</code>```

Explanation:

First, we get the input and take the modulus.

```<code>  ? { ?
 . . . .
' % . . .
 . . . .
  . . .
</code>```

Then, it checks if the modulus is 0 or not. If it is, the IP turns 60 degrees left, bounces off the mirror, sets the cell to 1 and prints.

Then, the IP continues onto the fourth row. When it reaches the >, it turns to the right instead (because the value of the cell is now 1). It goes oob, and comes back in the bottom right corner heading NW. The IP hits the <, goes along the top row, and comes back in the right corner to hit the @, stopping the program.

```<code>  . . .
 ! 1 \ .
. . < @ .
 > . . .
  . . .
</code>```

If the modulus turns out to be positive, the IP turns 60 degrees to the right. Once it goes out the bottom right corner, it continues on the bottom left edge because of Hexagony's wrapping rules. The ' is reused to make the IP go to a cell with 0 in it. The IP then travels along the fourth row, wraps around to the second, hits print, and gets reflected into the <. The rest of the path to the @ is the same.

```<code>  . . .
 ! . \ .
' . < @ .
 > . . .
  . . .
</code>```

That's some serious wizardry.

@FryAmTheEggman's Solution (12):

Unformatted:

```<code>?{?\!1@'%\!(
</code>```

Formatted:

```<code>  ? { ?
 \ ! 1 @
' % \ ! (
 . . . .
  . . .
</code>```

Explanation:

Like the other solutions, it gets the input and takes the modulus.

```<code>?{?..>1'%<.@!'/
</code>```0

Then, the IP gets deflected into the bottom corner. If the modulus is positive, it goes on the top left edge. The ? has no more input, so it sets the cell to 0. The ! then prints the 0, and the @ terminates the program.

```<code>?{?..>1'%<.@!'/
</code>```1

Things are much trickier for when the modulus is 0. First of all, it gets decremented, then reset to 0, then set to 1, then printed. Then, the 1 gets decremented to 0. After that, the program runs like it does at the beginning until it tries to do 0%0. That makes it throw a silent error and quit.

```<code>?{?..>1'%<.@!'/
</code>```2

I really like the silent error trick, but a simpler way would be to replace the ( with / so that the IP passes through the first time, but gets reflected into @ the second.

Collaborative solution (10):

Unformatted:

```<code>?{?!1\@'%<
</code>```

Formatted:

```<code>  ? { ?
 ! 1 \ @
' % < . .
 . . . .
  . . .
</code>```

This program starts out the same as all the other programs, getting the input and modding it.

If the input is 0, the IP turns left when it hits <. It gets deflected into 1!@, which prints 1 and quits.

```<code>  . . .
 ! 1 \ @
. . < . .
 . . . .
  . . .
</code>```

If the input is positive, the IP turns right when it hits <. It exits through the corner, and goes along the top right edge hitting the @ without printing.

```<code>  . . ?
 . . . @
. . < . .
 . . . .
  . . .
</code>```

Title: Divisibility test

Body:
Hexagony, <s>15, 13, 12</s> 10 bytes

Everybody's favorite hexagon-based language! :D

TL;DR works using magic, unformatted solutions in decreasing byte count:

?{?..>1'%<.@!'/
?{?!1\.'%<@.>
?{?\!1@'%\!(
?{?!1\@'%<

Saved 2 bytes thanks to @MartinEnder's layout wizardry.

@FryAmTheEggman saved 1 byte by using the corners more creatively

Both @MartinEnder and @FryAmTheEggman came up with a 10 byte solution that doesn't print anything for falsely values.

My solution (15):

Unformatted:

?{?..>1'%<.@!'/

Formatted:

  ? { ?
 . . > 1
' % < . @
 ! ' / .
  . . .

@Martin Ender's Solution (13):

Unformatted:

?{?!1\.'%<@.>

Formatted:

  ? { ?
 ! 1 \ .
' % < @ .
 > . . .
  . . .

Explanation:

First, we get the input and take the modulus.

  ? { ?
 . . . .
' % . . .
 . . . .
  . . .

Then, it checks if the modulus is 0 or not. If it is, the IP turns 60 degrees left, bounces off the mirror, sets the cell to 1 and prints.

Then, the IP continues onto the fourth row. When it reaches the >, it turns to the right instead (because the value of the cell is now 1). It goes oob, and comes back in the bottom right corner heading NW. The IP hits the <, goes along the top row, and comes back in the right corner to hit the @, stopping the program.

  . . .
 ! 1 \ .
. . < @ .
 > . . .
  . . .

If the modulus turns out to be positive, the IP turns 60 degrees to the right. Once it goes out the bottom right corner, it continues on the bottom left edge because of Hexagony's wrapping rules. The ' is reused to make the IP go to a cell with 0 in it. The IP then travels along the fourth row, wraps around to the second, hits print, and gets reflected into the <. The rest of the path to the @ is the same.

  . . .
 ! . \ .
' . < @ .
 > . . .
  . . .

That's some serious wizardry.

@FryAmTheEggman's Solution (12):

Unformatted:

?{?\!1@'%\!(

Formatted:

  ? { ?
 \ ! 1 @
' % \ ! (
 . . . .
  . . .

Explanation:

Like the other solutions, it gets the input and takes the modulus.

  ? { ?
 . . . .
' % . . .
 . . . .
  . . .

Then, the IP gets deflected into the bottom corner. If the modulus is positive, it goes on the top left edge. The ? has no more input, so it sets the cell to 0. The ! then prints the 0, and the @ terminates the program.

  ? . .
 \ ! . @
. . \ . .
 . . . .
  . . .

Things are much trickier for when the modulus is 0. First of all, it gets decremented, then reset to 0, then set to 1, then printed. Then, the 1 gets decremented to 0. After that, the program runs like it does at the beginning until it tries to do 0%0. That makes it throw a silent error and quit.

  ? { ?
 . . 1 .
' % \ ! (
 . . . .
  . . .

I really like the silent error trick, but a simpler way would be to replace the ( with / so that the IP passes through the first time, but gets reflected into @ the second.

Collaborative solution (10):

Unformatted:

?{?!1\@'%<

Formatted:

  ? { ?
 ! 1 \ @
' % < . .
 . . . .
  . . .

This program starts out the same as all the other programs, getting the input and modding it.

If the input is 0, the IP turns left when it hits <. It gets deflected into 1!@, which prints 1 and quits.

  . . .
 ! 1 \ @
. . < . .
 . . . .
  . . .

If the input is positive, the IP turns right when it hits <. It exits through the corner, and goes along the top right edge hitting the @ without printing.

  . . ?
 . . . @
. . < . .
 . . . .
  . . .


答:
Jelly, 6 bytes

```<code>ṫJḣ"ḅ1
</code>```

Try it online! or verify all test cases.

How it works

```<code>ṫJḣ"ḅ1  Main link. Argument: A (array)

 J      Index; yield the 1-based indices of A.
ṫ       Tail; map k to the postfix of A that begins with the k-th element.
  ḣ"    Vectorized head; for each k in A, truncate the corr. postfix to length k.
    ḅ1  Convert the resulting slices from base 1 to integer.
</code>```

Title: Substring Sum Set

Body:
Jelly, 6 bytes

ṫJḣ"ḅ1

Try it online! or verify all test cases.

How it works

ṫJḣ"ḅ1  Main link. Argument: A (array)

 J      Index; yield the 1-based indices of A.
ṫ       Tail; map k to the postfix of A that begins with the k-th element.
  ḣ"    Vectorized head; for each k in A, truncate the corr. postfix to length k.
    ḅ1  Convert the resulting slices from base 1 to integer.