109
\$\begingroup\$

As of 13/03/2018 16:45 UTC, the winner is answer #345, by Khuldraeseth na'Barya. This means the contest is officially over, but feel free to continue posting answers, just so long as they follow the rules.

As well, just a quick shout out to the top three answerers in terms of numbers of answers:

1. NieDzejkob - 41 answers

2. KSmarts - 30 answers

3. Hyper Neutrino - 26 answers


This is an answer chaining question that uses sequences from OEIS, and the length of the previous submission.

This answer chaining question will work in the following way:

  • I will post the first answer. All other solutions must stem from that.
  • The next user (let's call them userA) will find the OEIS sequence in which its index number (see below) is the same as the length of my code.
  • Using the sequence, they must then code, in an unused language, a program that takes an integer as input, n, and outputs the nth number in that sequence.
  • Next, they post their solution after mine, and a new user (userB) must repeat the same thing.

The nth term of a sequence is the term n times after the first, working with the first value being the first value given on its OEIS page. In this question, we will use 0-indexing for these sequences. For example, with A000242 and n = 3, the correct result would be 25.

However!

This is not a , so shortest code doesn't matter. But the length of your code does still have an impact. To prevent the duplication of sequences, your bytecount must be unique. This means that no other program submitted here can be the same length in bytes as yours.

If there isn't a sequence for then length of the last post, then the sequence for your post is the lowest unused sequence. This means that the sequences used also have to be unique, and that the sequence cannot be the same as your bytecount.

After an answer has been posted and no new answers have been posted for more than a week, the answer before the last posted (the one who didn't break the chain) will win.

Input and Output

Generic input and output rules apply. Input must be an integer or a string representation of an integer and output must be the correct value in the sequence.

Formatting

As with most questions, please format your answer like this

# N. language, length, [sequence](link)

`code`

[next sequence](link)

*anything else*

Rules

  • You must wait for at least 1 hour before posting an answer, after having posted.
  • You may not post twice (or more) in a row.
  • The index number of a sequence is the number after the A part, and with leading zeros removed (e.g. for A000040 the index number is 40)
  • You can assume that neither the input nor the required output will be outside your languages numerical range, but please don't abuse this by choosing a language that can only use the number 1, for example.
  • If the length of your submission is greater than 65536 characters long, please provide a link to a way to access the code (pastebin for example).
  • n will never be larger than 1000, or be out of bounds for the sequence, simply to prevent accuracy discrepancies from stopping a language from competing.
  • Every 150 (valid) answers, the number of times a language may be used increases. So after 150 solutions have been posted, every language may be used twice (with all previous answers counting towards this). For instance, when 150 answers have been posted, Python 3 may be used twice, but due to the fact that it has already been used once, this means it can only be used once more until 300 answers have been posted.
  • Please be helpful and post a link to the next sequence to be used. This isn't required, but is a recommendation.
  • Different versions of languages, e.g. Python 2 and Python 3 are different languages. As a general rule, if the different versions are both available on Try It Online, they are different languages, but keep in mind that this is a general rule and not a rigid answer.
  • It is not banned, but please try not to copy the code from the OEIS page, and actually try to solve it.
  • Hardcoding is only allowed if the sequence is finite. Please note that the answer that prompted this (#40) is the exception to the rule. A few answers early in the chain hardcode, but these can be ignored, as there is no good in deleting the chain up to, say, #100.

Answer chain snippet

var QUESTION_ID=133754,OVERRIDE_USER=66833;function shareUrl(i){return"https://codegolf.stackexchange.com/a/"+i}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 getTemplate(s){return jQuery(jQuery("#answer-template").html().replace("{{PLACE}}",s.index+".").replace("{{NAME}}",s.user).replace("{{LANGUAGE}}",s.language).replace("{{SEQUENCE}}",s.sequence).replace("{{SIZE}}",s.size).replace("{{LINK}}",s.link))}function search(l,q){m=jQuery("<tbody id='answers'></tbody>");e.forEach(function(s){if(!q||(l==0&&RegExp('^'+q,'i').exec(s.lang_name))||(l==1&&q===''+s.size)){m.append(jQuery(getTemplate(s)))}});jQuery("#answers").remove();jQuery(".answer-list").append(m)}function sortby(ix){t=document.querySelector('#answers');_els=t.querySelectorAll('tr');els=[];for(var i=0;i<_els.length;i++){els.push(_els[i]);}els.sortBy(function(a){a=a.cells[ix].innerText;return ix==0||ix==4?Number(a):a.toLowerCase()});for(var i=0;i<els.length;i++)t.appendChild(els[i]);}function checkSize(x){if(!x)return jQuery("#size-used").text("");var i=b.indexOf(+x);if(i<0)return jQuery("#size-used").text("Available!");var low=+x,high=+x;while(~b.indexOf(low))low--;while(~b.indexOf(high))high++;jQuery("#size-used").text(("Not available. The nearest are "+low+" and "+high).replace("are 0 and","is"))}function checkLang(x){}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.answer_id;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.user_id==OVERRIDE_USER?"<span id='question-author'>"+e.owner.display_name+"</span>":e.owner.display_name)}function process(){b=[];c=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);if(a){e.push({user:getAuthorName(s),size:+a[4],language:a[2],lang_name:a[3],index:+a[1],sequence:a[5],link:shareUrl(s.answer_id)});if(b.indexOf(+a[4])>=0&&c.indexOf(+a[4])<0){c.push(+a[4])};b.push(+a[4])}else{jQuery('#weird-answers').append('<a href="'+shareUrl(s.answer_id)+'">This answer</a> is not formatted correctly. <b>Do not trust the information provided by this snippet until this message disappears.</b><br />')}}),e.sortBy(function(e){return e.index});e.forEach(function(e){jQuery("#answers").append(getTemplate(e))});var q="A"+("000000"+e.slice(-1)[0].size).slice(-6);jQuery("#next").html("<a href='http://oeis.org/"+q+"'>"+q+"</a>");c.forEach(function(n){jQuery('#weird-answers').append('The bytecount '+n+' was used more than once!<br />')})}Array.prototype.sortBy=function(f){return this.sort(function(a,b){if(f)a=f(a),b=f(b);return(a>b)-(a<b)})};var ANSWER_FILTER="!*RB.h_b*K(IAWbmRBLe",COMMENT_FILTER="!owfmI7e3fd9oB",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page,e=[];getAnswers();var SCORE_REG=/<h\d>\s*(\d+)\.\s*((?:<a [^>]+>\s*)?((?:[^\n,](?!<\/a>))*[^\s,])(?:<\/a>)?),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*, ((?:<a[^>]+>\s*)?A\d+(?:\s*<\/a>)?)\s*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important;font-family:Roboto,sans-serif}#answer-list,#language-list{padding:10px;/*width:290px*/;float:left;display:flex;flex-wrap:wrap;list-style:none;}table thead{font-weight:700}table td{padding:5px}ul{margin:0px}#board{display:flex;flex-direction:column;}#language-list li{padding:2px 5px;}#langs-tit{margin-bottom:5px}#byte-counts{display:block;margin-left:15px;}#question-author{color:purple;text-shadow: 0 0 15px rgba(128,0,128,0.1);}#label-info{font-weight: normal;font-size: 14px;font-style: italic;color: dimgray;padding-left: 10px;vertical-align: middle; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><p id="weird-answers"></p><p>Currently waiting on <span id="next"></span></p><span>Search by Byte Count: <input id="search" type="number" min=1 oninput="checkSize(this.value);search(1,this.value)" onclick="document.getElementById('search2').value='';!this.value&&search(0,'')"/> <span id="size-used"></span></span><br><span>Search by Language: <input id="search2" oninput="checkLang(this.value);search(0,this.value)" onclick="document.getElementById('search').value='';!this.value&&search(0,'')"/> <span id="language-used"></span></span><h2>Answer chain <span id="label-info">click a label to sort by column</span></h2><table class="answer-list"><thead><tr><td  onclick="sortby(0)">#</td><td onclick="sortby(1)">Author</td><td onclick="sortby(2)">Language</td><td onclick="sortby(3)">Sequence</td><td onclick="sortby(4)">Size</td></tr></thead><tbody id="answers"></tbody></table><table style="display: none"><tbody id="answer-template"><tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"><tbody id="language-template"><tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SEQUENCE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>

\$\endgroup\$
13
  • \$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$
    – Dennis
    Oct 31, 2017 at 2:49
  • \$\begingroup\$ Is it OK if a program would need a better floating-point accuracy for the builtin float/double type in order to produce values for larger n? \$\endgroup\$
    – Maya
    Nov 21, 2017 at 15:15
  • 1
    \$\begingroup\$ @Giuseppe No, as you're generating the numbers by doing the maths, rather than just placing them into an array/string \$\endgroup\$ Dec 15, 2017 at 22:14
  • 2
    \$\begingroup\$ @cairdcoinheringaahing In my opinion that's hardcoding the gamma constant. It doesn't work "in theory" for larger numbers. \$\endgroup\$
    – DELETE_ME
    Dec 22, 2017 at 12:44
  • 6
    \$\begingroup\$ Chat room \$\endgroup\$
    – DELETE_ME
    Dec 22, 2017 at 12:45

406 Answers 406

1
5 6
7
8 9
14
3
\$\begingroup\$

248. Huginn, 904 bytes, A000087

import Algorithms as alg;

gcd( a_, b_ ) {
 u = integer( a_ );
 v = integer( b_ );
 while ( v > 0 ) {
    t = u;
    u = v;
    v = t % v;
  }
  return( u );
}

eulerPhi( n_ ) {
 n = integer( n_ );
 x = 0;
 for ( i : alg.range( 1, n + 1 ) ) {
  if ( gcd( i, n ) == 1 ) {
   x += 1;
  }
 }
 return ( x );
}

binomial( n_, k_ ) {
 n = integer( n_ );
 k = integer( k_ );
 x = 1;
 for ( i : alg.range( 1, k + 1 ) ) {
  x = x * (n - i + 1) / i;
 }
 return ( x );
}

A000087( n_ ) {
 n = integer( n_ ) + 1;
 z = 0.0 ;
 for ( k : alg.range( 1, n ) ) {
  if ( n % k == 0 ) {
   z += real( eulerPhi( n / k ) * binomial( 3 * k, k ) );
  }
 }
 z += real( ( n + 2 ) * binomial( 3 * n, n ) ) / real( ( 3 * n - 2 ) * ( 3 * n - 1 ) );
 z = z / real( 3 * n );
 if ( n % 2 == 1 ) {
  z += real( 2 * ( n + 1 ) * binomial( 3 * ( n + 1 ) / 2, ( n + 1 ) / 2 ) ) / real( 3 * ( 3 * n - 1 ) * ( 3 * n + 1 ) );
 }
 return( z );
}

Next Sequence

Try it online!

This uses the formula from the OEIS page, which is a little complicated, but not too hard once you break it down.

\$\endgroup\$
1
3
\$\begingroup\$

251. C (tcc), 269 bytes, A000711

long p(int k,int n,int*a,int l){long s=1;if(n<1)return!l;a[l]=n;for(int i=1,c,j;i<=k;i++){for(j=0,c=1;j<=l;j++)if(a[j]==i)c++;s*=(i<5)?((c)*(c+1)/2):c;}for(int i=(l==0)?1:a[l-1];i<=n/2;i++)a[l]=i,s+=p(k,n-i,a,l+1);return s;}long a(int n){int a[1000];return p(n,n,a,0);}

Try it online!

Next sequence!

Explanation

// Takes a partition a of the number k and returns how many different
// partitions it represents if the numbers can have many kinds, according
// to the specification of the sequence. For example:
// [1 1 1] =>
//    [1  1  1 ]
//    [1  1  1']
//    [1  1' 1']
//    [1' 1' 1']
//    [1' 1' 1"]
//    [1' 1" 1"]
//    [1" 1" 1"]
// Each different number in the partition can be processed separately,
// and the "score" will be the product of the scores of each number.
long score(int k, int length, int * a){
    long product = 1;

    for(int i = 1;i <= k;i++){ // A partition of k can contain numbers [1,k]
        int count = 0; // Count how many times the number i appears
        for(int j = 0;j <= length;j++){
            if(a[j] == i) c++;
        }

        if(i < 5){
            // i has 3 kinds. If you sort all the cases in ascending
            // "kind numbers", then the first Kind 2 (') can be in
            // (number of Kind >= 1, i. e. the variable c) + 1 positions:
            //    1  1  1
            //    1  1  1'
            //    1  1' 1'
            //    1' 1' 1'
            // Then, the first Kind 3 (") can be in (number of Kind >= 2) + 1
            // positions:
            //    1' 1' 1'
            //    1' 1' 1"
            //    1' 1" 1"
            //    1" 1" 1"
            // If you think about it, you'll get the sum of natural numbers
            // from 1 to (c + 1), for which there is a nice closed form
            // formula (look at sequence of answer number 1, don't forget
            // to rate the language choice 😉) (one problem Emoji solved
            // is ending a parenthesis with an emoticon).
            product *= ((c + 1) * (c + 2)) / 2;
        }else{
            product *= (c + 1);
        }
    }

    return product;
}

// A recursive function that enumerates all partitions of n, scores each
// and returns the sum of all scores. The partitions are generated at
// (a + level)
// Pseudocode algorithm:
// def partitions(n):
//     yield [n]
//     for i in range(1, n):
//         for p in partitions(n - i):
//             yield [n] + p
// Notice how we don't really need to check the whole range of [1, n)
// k is only relevant for scoring
// the partitions are generated at (a + level)
long partitions(int k, int n, int * a, int level){
    if(n < 1){
        if(l == 0){
            return 1; // l == 0 => this is the top level call, so include
            // the case of []
        }else{
            return 0; // doesn't happen, but I think this is the best
            // way to handle this edge case
        }
    }

    a[l] = n;
    long score_sum = score(k, l + 1, a);

    int start;

    if(l == 0){
        start = 1;
    }else{
        start = a[l - 1];
    }

    for(int i = start;i <= n/2;i++){
        a[l]=i;
        score_sum += partitions(k,n-i,a,l+1);
    }

    return score_sum;
}

long a(int n){
    // the longest partition of k is [1]*k, speaking Python,
    // so let's not bother with dynamic allocation
    int a[1000];
    return partitions(n, n, a, 0);
}
\$\endgroup\$
9
  • \$\begingroup\$ My Jelly code: chat.stackexchange.com/transcript/message/41118715#41118715 \$\endgroup\$
    – DELETE_ME
    Nov 13, 2017 at 14:14
  • \$\begingroup\$ Please don't golf your answer, make it readable instead. This isn't even code-golf. \$\endgroup\$
    – DELETE_ME
    Nov 13, 2017 at 14:36
  • 1
    \$\begingroup\$ @user202729 but it's fun! OK, I'll add a readable version \$\endgroup\$
    – Maya
    Nov 13, 2017 at 14:46
  • \$\begingroup\$ My Jelly code is even more efficient than yours, and only at number of bytecount ~ 8.2% of yours. \$\endgroup\$
    – DELETE_ME
    Nov 13, 2017 at 14:52
  • \$\begingroup\$ @user202729 But is it more readable? \$\endgroup\$ Nov 13, 2017 at 15:05
3
\$\begingroup\$

252. Pari/GP, 251 bytes, A000269

A000081(n) = if( n<3, if(n<1,0,1) , 1/(n-1)*sum(k=1,n-1,sumdiv(k,d,d*A000081(d))*A000081(n-k) ) );

gfA81(n) = sum( i=0, n, A000081(i)*x^i, O(x^(n+1)) );

gfA269(n) = {Bx = gfA81(n); Bx^3 * (3-2*Bx) / (1-Bx)^3}

A000269(n) = polcoeff(gfA269(n+3), n+3)

Next Sequence

Try it online!

This uses the generating function formula, by directly computing values of the sequence A000081.

\$\endgroup\$
6
  • \$\begingroup\$ Does anyone have access to that paper? I don't see how we're supposed that in less than O(silly(n))... \$\endgroup\$
    – Maya
    Nov 16, 2017 at 8:48
  • \$\begingroup\$ @NieDzejkob I have it now. I can implement the sequence in Haskell with the usual stuff for handling generating functions plus three one-line definitions. \$\endgroup\$ Nov 16, 2017 at 23:12
  • \$\begingroup\$ @NieDzejkob It doesn't have to be efficient. \$\endgroup\$
    – KSmarts
    Nov 17, 2017 at 14:13
  • \$\begingroup\$ @KSmarts if it's fast enough for small n that you can convince yourself that it works... \$\endgroup\$
    – Maya
    Nov 17, 2017 at 18:04
  • \$\begingroup\$ Rip challenge :( \$\endgroup\$ Nov 20, 2017 at 3:53
3
\$\begingroup\$

267. Erlang (escript), 338 bytes, A002572


h(N,A,_) when A > N -> 0;
h(N,A,_) when A == N -> 1;
h(N,A,B) -> case erlang:get({N,A,B}) of
	F when is_integer(F) -> F;
	'undefined' -> 
		F = lists:sum(lists:map(
			fun(I) -> h(N-I, (A-I)*2, B+1) end,
		lists:seq(0, A-1))),
		erlang:put({N,A,B}, F),
		F
	end.

main([])-> {ok, [N]} = io:fread("", "~d"),
io:fwrite("~p", [h(N+1,1,0)]).

Try it online!

Next sequence!

I first wrote this in Python, and then I had decided to find a language with bignums, because this sequence grows pretty quickly. I hope this will explain it pretty well:

cache = {}
# Calculate the number of partitions of a/(2^b) into n powers of (1/2), with
# the exponent of at least b. You need at least a powers of (1/2) for the
# trivial solution of a*(1/2)^b, and you cannot write any of the fractions
# in that solution as a sum of smaller fractions if a = n.
def B(n, a, b):
    if a > n:
        return 0

    if a == n:
        return 1
    
    if (n, a, b) not in cache:
# We need more fractions - use 1/(2^b) from 0 to (a-1) times, and fill
# the rest with the recursive call of this function

        s = 0
        for i in range(a):
            s += B(n - i, # we used i fractions
                   (a - i) * 2, # use a higher power of (1/2)
                   b + 1)
        cache[(n, a, b)] = s

    return cache[(n, a, b)]

def A(n):
    return B(n, 1, 0)

for n in range(1, 2000):
    print(n, A(n))

Memoization in Erlang from this SO answer

\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 from me. I really don't understand your ability to port stuff that easily to new languages. \$\endgroup\$
    – Mr. Xcoder
    Nov 30, 2017 at 18:57
3
\$\begingroup\$

268. Pyke, 99 bytes, A000338

9 2/Q2+X*15 2/Q2+*-BQ1>*Q0q5*Q1q18*++                                                              

Try it here!

Next sequence. (quite tendious, yet doable I think)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The next sequence is definitely doable. It looks more tedious than hard to me. \$\endgroup\$
    – KSmarts
    Nov 30, 2017 at 19:38
3
\$\begingroup\$

269. Pip, 118 bytes, A000099

n:0
m:0
++a
W a {
  ++n
  Y -n\,n
  AA:{$+a*a<=n} MS yCPy
  VV:PI*n
  PP:AA-VV
  I ABPP>m {
    m:ABPP
    --a
  }
}
n

Try it online! (times out for indices greater than 7)

Next sequence

Commented

Implements the definition of the sequence:

n:0            Index of helper sequences
m:0            Max value of |P(n)| so far
++a            Index of main sequence (++ because the definition is 1-indexed)
W a {          Count down until a hits 0:
  ++n           Increment index of helper sequence
  Y -n\,n       Yank inclusive range [-n, n]
  AA:           Sequence A(n) is:
    {$+a*a<=n}   Function: Square items of list, sum, and check <= n
    MS           Map-sum
    yCPy         Cartesian product of y with itself
  VV:PI*n       Sequence V(n) is pi times n
  PP:AA-VV      Sequence P(n) is A(n)-V(n)
  I ABPP>m {    If abs(P(n)) > current max value:
    m:ABPP       Max is abs(P(n))
    --a          Decrement index of main sequence
  }
}
n              Output index of helper sequence at the a'th maximum
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Did you check that the Pi constant has enough accuracy to compute 1000 terms? \$\endgroup\$
    – Maya
    Nov 30, 2017 at 21:32
  • \$\begingroup\$ @NieDzejkob I believe it will. It's got about 16 significant digits, and if the series is ~= 0.0139 * n^4 (which is a pretty good fit for the first 200 terms), it should only require 11 significant digits to compute n = 1000. But I would have to compute that many terms to find out, and that would take days. Maybe I could write a C program to check... \$\endgroup\$
    – DLosc
    Nov 30, 2017 at 21:48
3
\$\begingroup\$

134. Emoji, 277 bytes, A000643

📥💬i💬📲
💬0💬📥👥
⛽
💬i💬📱👥💬1💬📥🌊💬i💬📲💬1💬📥🐔
🚘⛽
💬1💬📥⛽
🔀👥💬1💬📥🌊🔀💬0💬📥🐔
🚘⛽
🔀💬2💬📥👪
🚘🔃🔚🐧🔀👥💬t💬📲👫💬t💬📱
🚘🔃🔀➡

Try it online!

Next sequence!

Explanation:

In contrast to Emojicode, Emoji is an esoteric programming language. Emoji is similar to GolfScript and CJam in that it uses a stack as the primary memory.

		Implicitly push all arguments as string. Stack: "7"
📥		Floor. Normally 🔢 would be used to get a float, but using
		floor gives an int, which (since the interpreter is written
		in Python) is a bignum. Stack: 7
💬i💬📲		Store to variable i. Stack:
💬0💬📥👥		Push "0", to string, duplicate. Stack: a(1) a(0)
⛽...🚘⛽...🚘🔃	While(...) do ... (let's look later in the loop)
💬i💬📱		(in while condition) recall variable i. Stack: a(4) a(3) i
👥		Duplicate. Stack: a(4) a(3) i i
💬1💬📥🌊		Subtract 1. Stack: a(4) a(3) i i-1
💬i💬📲		Store i-1 to i for next iteration. Stack: a(4) a(3) i
💬1💬📥🐔		Is greater than 1? This means that the outer loop will be
		repeated n - 1 times, where n is the input.
		Stack: a(4) a(3) true
💬1💬📥		(in outer loop) Now we will calculate 2^a(3) - push 1.
		Stack: a(4) a(3) 1
⛽...🚘⛽...🚘🔃	While(...) do ... (now a(3) is the loop counter, let's assume
		we are at the last iteration of this loop.)
🔀		Swap. Stack: a(4) 2^(a(3)-1) 1
👥		Duplicate. Stack: a(4) 2^(a(3)-1) 1 1
💬1💬📥🌊		Subtract 1. Stack: a(4) 2^(a(3)-1) 1 0
🔀		Swap. Stack: a(4) 2^(a(3)-1) 0 1
💬0💬📥🐔		Is greater than 0? This means that the inner loop will be
		repeated a(3) times. Stack: a(4) 2^(a(3)-1) 0 true. Notice
		that after true is popped, the two values are swapped compared
		to the beginning of the condition evaluation. This has to be
		fixed both in the inner loop and after it.
🔀		(in inner loop) swap. Stack: a(4) 0 2^(a(3)-1)
💬2💬📥👪		Multiply by 2. Stack: a(4) 0 2^a(3).
		The loop ends. Stack: a(4) 2^a(3) 0
🔚🐧		The counter is now always 0 and has to be discarded. Since
		there is no such instruction, an empty if is used instead.
		Stack: a(4) 2^a(3)
🔀		Swap. Stack: 2^a(3) a(4)
👥💬t💬📲		Duplicate and store a(4) in t. Stack: 2^a(3) a(4)
👫		Add. Stack: a(5)
💬t💬📱		Restore a(4) from variable. Stack: a(5) a(4).
		The loop ends here. Stack: a(7) a(6).
🔀		Swap. Stack: a(6) a(7).
➡		Print a(7). The stack is discarded at the end of the program.

Emoji aren't fixed-width in a fixed-width font, so spaces don't work for alignment. Fortunately, tabs work, but different emoji fonts might slightly break it.

\$\endgroup\$
2
  • \$\begingroup\$ ಠ_ಠ I have a feeling that you might get the bounty when it's finally awarded :P \$\endgroup\$ Sep 4, 2017 at 9:58
  • \$\begingroup\$ @cairdcoinheringaahing Unless someone posts an answer in Malbolge, a. k. a. you are probably right. Have you seen 99 bottles of beer in this? \$\endgroup\$
    – Maya
    Sep 4, 2017 at 10:50
3
\$\begingroup\$

143. Excel, 120 bytes, A000782

=2*FACT(2*A1)/(FACT(A1)*(FACT(A1+1)))-IFERROR(FACT(2*A1-2)/(FACT(A1-1)*(FACT(A1))),0)                                   

Next sequence!

Input is in cell A1. It just implements the function listed on OEIS:

a(n) = 2 * C(n) - C(n-1)
C(n) = (2n)! / (n!(n+1)!)

Technically, only n > 0 should be valid so the IFERROR bit could be dropped since it only errors on n < 1. I left it in for artistic license and to have what I think is a more interesting next sequence.

\$\endgroup\$
3
\$\begingroup\$

200. shortC, 189 bytes, A000092

Note: byte count includes the +3 bytes for -lm.

f(x){Lr=0,d=0,n=1;O;d<x+1;n++){Lc=0,m=ceil(sqrt(n))+1,i=-m,j,k;O;i<m;i++)Oj=-m;j<m;j++)Ok=-m;k<m;k++)c+=i*i+j*j+k*k<=n;c-=lround(sqrt(n*n*n)*4.18879020478639);c=abs(c);Fc>r)d++,r=c;}Tn-1

Try it online!

Next sequence!

Yay, 200th answer.

\$\endgroup\$
3
  • \$\begingroup\$ For the next sequence, x < n (modulo implies it but it wasn't immediately obvious to me). \$\endgroup\$
    – Maya
    Oct 2, 2017 at 21:37
  • 1
    \$\begingroup\$ Well, that's 200. I'm not sure whether to be glad or astounded that anyone still cares about this challenge :P \$\endgroup\$ Oct 2, 2017 at 21:51
  • \$\begingroup\$ @cairdcoinheringaahing that means that you came up with an interesting challenge. You should be proud. \$\endgroup\$
    – Maya
    Oct 3, 2017 at 10:31
3
\$\begingroup\$

201. Nim, 213 bytes, A000189

from strutils import parseint
import math

proc A000189(index: int): int =
  result=1
  for x in 1..index-1:
    if x^3 mod index == 0:
      result = result + 1
  return

echo A000189(parseint(readline(stdin))+1)

Try it online!

Next Sequence.

\$\endgroup\$
1
  • \$\begingroup\$ Darn I had a Brain-Flak solution coming :P Oh well it was nowhere near done anyway xD \$\endgroup\$
    – hyper-neutrino
    Oct 2, 2017 at 22:58
3
\$\begingroup\$

274. ArnoldC, 1021 bytes, A000123

IT'S SHOWTIME
HEY CHRISTMAS TREE INPUT
YOU SET US UP @I LIED
HEY CHRISTMAS TREE OUTPUT
YOU SET US UP @I LIED
GET YOUR ASS TO MARS INPUT
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
GET YOUR ASS TO MARS OUTPUT
DO IT NOW A000123 INPUT
TALK TO THE HAND OUTPUT
YOU HAVE BEEN TERMINATED

LISTEN TO ME VERY CAREFULLY A000123
I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE INDEX
GIVE THESE PEOPLE AIR
HEY CHRISTMAS TREE NUMBER1
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE NUMBER2
YOU SET US UP @NO PROBLEMO
BECAUSE I'M GOING TO SAY PLEASE INDEX
GET TO THE CHOPPER NUMBER1
HERE IS MY INVITATION INDEX
GET DOWN 1
ENOUGH TALK
GET TO THE CHOPPER NUMBER2
HERE IS MY INVITATION INDEX
HE HAD TO SPLIT 2
ENOUGH TALK
GET YOUR ASS TO MARS NUMBER1
DO IT NOW A000123 NUMBER1
GET YOUR ASS TO MARS NUMBER2
DO IT NOW A000123 NUMBER2
GET TO THE CHOPPER NUMBER1
HERE IS MY INVITATION NUMBER1
GET UP NUMBER2
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
I'LL BE BACK NUMBER1
HASTA LA VISTA, BABY

Try it online!

Next Sequence

Uses the recurrence relation a(n) = a(n-1) + a(floor(n/2))

\$\endgroup\$
3
\$\begingroup\$

272. SNOBOL4 (CSNOBOL4), 129 bytes, A010008

	INPUT('READLINE', 5)
	IN = READLINE
	OUTPUT('PRINT', 6)
	EQ(IN,0)			:S(OK)	
	OUTPUT = 18 * IN * IN + 2	:(END)
OK
	OUTPUT = 1
END

Try it online!

Next sequence

I think I could probably write another answer in SNOBOL; it took me a good ten minutes to figure out how to do I/O because I'm dumb, and I'm lucky the sequence was so stupidly easy.

Explanation:

SNOBOL is pretty old, so it has some weird quirks for someone who's been using more "modern" languages. First of all, you have to indent lines, because un-indented lines are labels. Control flow is purely through GOTOs, labels, and SUCCESS/FAILURE of a line. And I'm still not sure about how to write a comment.

INPUT('READLINE', 5) sets a variable READLINE that takes input from file 5, which is by default the keyboard/console input.

IN = READLINE reads a single line from the file as a string.

OUTPUT('PRINT', 6) sets a variable PRINT that prints to file 6, which is by default the console.

EQ(IN,0) tests for equality between the input and 0. The GOTO:S(OK) is the instruction "on Success, goto OK", so it jumps to OK, setting OUTPUT to 1, printing, and then hitting END.

Otherwise, it sets the output to 18*n^2+2 and jumps to the END, terminating the program.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I've heard that that kind of control flow is considered harmful. \$\endgroup\$
    – KSmarts
    Dec 7, 2017 at 20:25
3
\$\begingroup\$

278. Java 6, 5692 bytes, A000104

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;

final class Main {
	static final Set<Pair> offsets;

	static {
		offsets = new HashSet<Pair>();
		offsets.add(new Pair(0, +1));
		offsets.add(new Pair(0, -1));
		offsets.add(new Pair(+1, 0));
		offsets.add(new Pair(-1, 0));
	}

	static final class Pair {
		final int x, y;

		Pair(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public String toString() {
			return "(" + this.x + ", " + this.y + ")";
		}

		public boolean equals(Object other) {
			if (other == null) {
				return false;
			} else if (other instanceof Pair) {
				Pair pair = (Pair) other;
				return this.x == pair.x && this.y == pair.y;
			} else {
				return false;
			}
		}

		public int hashCode() {
			return this.x ^ this.y; // Expect many collisions with this hashcode; it's mostly just to make sure the hashset actually checks for equality) //
		}

		public Pair add(Pair pair) {
			return new Pair(this.x + pair.x, this.y + pair.y);
		}
	}

	private Main() {}

	public static Set<Pair> rotate(Set<Pair> polyomino) {
		Set<Pair> result = new HashSet<Pair>();
		for (Pair pair : polyomino)
			result.add(new Pair(-pair.y, pair.x));
		return result;
	}

	public static Set<Pair> conjugate(Set<Pair> polyomino) {
		Set<Pair> result = new HashSet<Pair>();
		for (Pair pair : polyomino)
			result.add(new Pair(pair.x, -pair.y));
		return result;
	}

	public static List<Set<Pair>> variants(Set<Pair> polyomino) {
		List<Set<Pair>> results = new ArrayList<Set<Pair>>();
		for (int x = 0; x < 4; x++) {
			polyomino = rotate(polyomino);
			results.add(polyomino);
			results.add(conjugate(polyomino));
		}
		return results;
	}

	public static Set<Integer> x(Set<Pair> polyomino) {
		Set<Integer> results = new HashSet<Integer>();
		for (Pair pair : polyomino)
			results.add(pair.x);
		return results;
	}

	public static Set<Integer> y(Set<Pair> polyomino) {
		Set<Integer> results = new HashSet<Integer>();
		for (Pair pair : polyomino)
			results.add(pair.y);
		return results;
	}

	public static int max(Set<Integer> set) {
		if (set.size() == 0) throw new IllegalArgumentException("max arg is an empty sequence");
		Iterator<Integer> iterator = set.iterator();
		int max = iterator.next();
		while (iterator.hasNext()) {
			int value = iterator.next();
			max = max > value ? max : value;
		}
		return max;
	}

	public static int min(Set<Integer> set) {
		if (set.size() == 0) throw new IllegalArgumentException("min arg is an empty sequence");
		Iterator<Integer> iterator = set.iterator();
		int min = iterator.next();
		while (iterator.hasNext()) {
			int value = iterator.next();
			min = min < value ? min : value;
		}
		return min;
	}

	public static Pair corner(Set<Pair> polyomino) {
		return new Pair(min(x(polyomino)), min(y(polyomino)));
	}

	public static Set<Pair> normalize(Set<Pair> polyomino) {
		Pair cn = corner(polyomino);
		Set<Pair> results = new HashSet<Pair>();
		for (Pair pair : polyomino)
			results.add(new Pair(pair.x - cn.x, pair.y - cn.y));
		return results;
	}

	public static boolean translations(Set<Pair> p1, Set<Pair> p2) {
		return normalize(p1).equals(normalize(p2));
	}

	public static boolean isomorphic(Set<Pair> p1, Set<Pair> p2) {
		for (Set<Pair> p : variants(p1))
			if (translations(p, p2))
				return true;
		return false;
	}

	public static boolean filled(Set<Pair> polyomino) {
		Set<Integer> x = x(polyomino);
		Set<Integer> y = y(polyomino);
		for (int i = min(x) + 1; i < max(x); i++) {
			for (int j = min(y) + 1; j < max(y); j++) {
				if (!polyomino.contains(new Pair(i, j))
				&&   polyomino.contains(new Pair(i, j + 1))
				&&   polyomino.contains(new Pair(i, j - 1))
				&&   polyomino.contains(new Pair(i + 1, j))
				&&   polyomino.contains(new Pair(i - 1, j)))
					return false;
			}
		}
		return true;
	}

	public static List<Set<Pair>> polyominoes(int cells) {
		List<Set<Pair>> results = new ArrayList<Set<Pair>>();
		if (cells == 0) {
			results.add(new HashSet<Pair>());
			return results;
		} else if (cells == 1) {
			Set<Pair> set = new HashSet<Pair>();
			set.add(new Pair(0, 0));
			results.add(set);
			return results;
		} else if (cells == 2) {
			Set<Pair> set = new HashSet<Pair>();
			set.add(new Pair(0, 0));
			set.add(new Pair(0, 1));
			results.add(set);
			return results;
		} else {
			for (Set<Pair> polyomino : polyominoes(cells - 1)) {
				for (Pair cell : polyomino) {
					for (Pair offset : offsets) {
						Set<Pair> variant = new HashSet<Pair>(polyomino);
						variant.add(cell.add(offset));
						if (variant.size() == cells) {
							results.add(variant);
						}
					}
				}
			}
		}
		List<Set<Pair>> output = new ArrayList<Set<Pair>>();
		outer: for (Set<Pair> r : results) {
			for (Set<Pair> p : output) {
				if (isomorphic(r, p)) {
					continue outer;
				}
			}
			if (filled(r)) output.add(r);
		}
		return output;
	}

	public static void main(String[] args) {
		boolean visualizer = true; // Change to `false` to not show visualizations
		int cells;
		List<Set<Pair>> polyominoes = polyominoes(cells = new Scanner(System.in).nextInt());
		System.out.println(polyominoes.size());
		if (cells != 0 && visualizer) {
			System.out.println();
			for (Set<Pair> polyomino : polyominoes) {
				Set<Integer> x = x(polyomino);
				Set<Integer> y = y(polyomino);
				int minx = min(x), maxx = max(x);
				int miny = min(y), maxy = max(y);
				for (int i = minx; i <= maxx; i++) {
					for (int j = miny; j <= maxy; j++) {
						System.out.print(polyomino.contains(new Pair(i, j)) ? '#' : '.');
					} System.out.println();
				} System.out.println();
			}
		}
	}
}

Try it online!

The TIO link links to the Java 8 interpreter but this answer works on Java 6 (tested locally thanks to user202729).

Next Sequence - this one has enough terms to be hardcoded but please don't.

Originally programmed in Python

\$\endgroup\$
5
  • \$\begingroup\$ Not enough. You need to support all n not "larger than 1000" - it means that all n such that 0 ≤ n ≤ 1000 need to be supported, that's 1001 terms. You are off by 1. \$\endgroup\$
    – DELETE_ME
    Dec 13, 2017 at 14:45
  • \$\begingroup\$ @user202729 lol oh. well, it's close :P In that case then, hardcoding it would require getting 1001 in which case one might as well solve it the correct way :p \$\endgroup\$
    – hyper-neutrino
    Dec 13, 2017 at 14:48
  • 2
    \$\begingroup\$ rules for the next sequence can be found here on page 13 since the OEIS page links to a JSTOR page and I didn't feel like registering there. \$\endgroup\$
    – Giuseppe
    Dec 13, 2017 at 14:48
  • \$\begingroup\$ HyperNeutrino: Do you want to turn off the visualizer? \$\endgroup\$
    – DELETE_ME
    Dec 13, 2017 at 14:49
  • \$\begingroup\$ @user202729 No, I intentionally left it on. I don't think it makes the output invalid since it obviously gives the correct answer, but if you want, I can turn it off; I can easily keep the bytecount the same. \$\endgroup\$
    – hyper-neutrino
    Dec 13, 2017 at 14:52
3
\$\begingroup\$

258. Forth (gforth), 329 bytes, A000144

: ODDQ 2 MOD ;
: EVENQ 1+ ODDQ ;
: DIVOK /MOD SWAP IF DROP 0 ELSE ODDQ THEN ;
: A2131 DUP 1+ 0 SWAP 1 ?DO OVER I DIVOK IF I + THEN LOOP NIP ;
: A186690 DUP A2131 SWAP EVENQ IF 0 SWAP - THEN ;
: ADVANCE DUP 1+ 0 SWAP 1 ?DO I 1+ PICK I A186690 * + LOOP 20 * OVER / SWAP 1+ ;
: A144 1 SWAP 1 SWAP 0 ?DO ADVANCE LOOP 1 ?DO NIP LOOP ;

Try it online!

Next sequence!

This time I managed to remove the surplus elements from the stack with 1 ?DO NIP LOOP.

\$\endgroup\$
10
  • \$\begingroup\$ Learn a new language just to use it twice... \$\endgroup\$
    – DELETE_ME
    Nov 21, 2017 at 9:55
  • \$\begingroup\$ @user202729 no, I learned it for a much larger project. It involves bootstrapping Linux from less than 1K binaries, and Forth is a good language thanks for its small interpreter. \$\endgroup\$
    – Maya
    Nov 21, 2017 at 10:36
  • \$\begingroup\$ I'm worried about the accuracy of the solution of the next sequence... This Jelly solution only survive up to n=13. \$\endgroup\$
    – DELETE_ME
    Nov 21, 2017 at 10:38
  • \$\begingroup\$ and is non-esoteric. BF interpreter is also small. \$\endgroup\$
    – DELETE_ME
    Nov 21, 2017 at 10:39
  • \$\begingroup\$ But why don't you just use assembly? \$\endgroup\$
    – DELETE_ME
    Nov 21, 2017 at 10:42
3
\$\begingroup\$

295. Unefunge-98 (PyFunge), 133 bytes, A000218

#z3&#rz#;::/3*j$.@1-\:a%:*\a/:a%:*\a/:*++\#;r
print(*map(lambda x:'pHra ywe!NY'[int(x, 16)], '%x'%(3*7*8*1821847*279590039)), sep='')

Next sequence!

Try it online!

#z3&#rz#;::/3*j$.@1-\:a%:*\a/:a%:*\a/:*++\#;r
#z                                            Kind of serves no purpose...
  3                                           Starting number of the sequence
   &                                          Input the number of iterations
    #rz#;                                 #;r Set up a way to jump to the
                                              beginning
         ::/                                  Make a copy of the loop counter and
                                              divide it by itself. Since 0/0 is
                                              defined as 0 in Funge, this leaves
                                              1 on the stack when the loop
                                              counter is not zero, but 0 when it
                                              is
            3*                                Multiply the result by 3 to skip
                                              $.@
              $.@                             When the loop ends, print the
                                              result
                 1-                           Decrement the loop counter
                   \:a%:*\a/:a%:*\a/:*++\     Calculate the next element of the
                                              sequence.
\$\endgroup\$
2
  • 1
    \$\begingroup\$ +1 for a Python polyglot! (For anyone reading this, try running it in Python 3) \$\endgroup\$ Dec 31, 2017 at 23:02
  • \$\begingroup\$ Befure running it, try to look and guess what it does. Should be easy to guess even if you don't know Python. \$\endgroup\$
    – DELETE_ME
    Jan 1, 2018 at 4:06
3
\$\begingroup\$

300. C# (.NET Core), 2407 bytes, A000137

using System;
using System.Numerics;

public class A000137 {

 // Expands the polynomial (1 / x^k)
 public static BigInteger[] ExpandReciprocalPowerK(int k, int max) {
  BigInteger[] result = new BigInteger[max + 1];
  for (int i = 0; i <= max; i++) {
   if (i % k == 0)
    result[i] = new BigInteger(1);
   else
    result[i] = new BigInteger(0);
  }
  return result;
 }

 // Calculates p1(x) * p2(x)
 public static BigInteger[] PolynomialMultiply(BigInteger[] x, BigInteger[] y, int max) {
  BigInteger[] result = new BigInteger[max + 1];
  for (int i = 0; i <= max; i++) {
   for (int j = 0; j <= max - i; j++) {
    if (result[i + j] == null)
     result[i + j] = new BigInteger(0);
    result[i + j] += x[i] * y[j];
   }
  }
  return result;
 }

 // Calculates (p(x))^n
 public static BigInteger[] PolynomialPower(BigInteger[] x, BigInteger n, int max) {
  BigInteger[] result = x;
  if (BigInteger.Compare(n, new BigInteger(0)) == 0) {
   result = new BigInteger[max + 1];
   result[0] = new BigInteger(1);
   for (int i = 1; i <= max; i++)
    result[i] = new BigInteger(0);
  }
  if (BigInteger.Compare(n, new BigInteger(2)) < 0)
   return result;

  BigInteger counter = new BigInteger(1);
  while (BigInteger.Compare(counter, n >> 2) <= 0)
   counter <<= 1;
  
  while (BigInteger.Compare(counter, new BigInteger(0)) > 0) {
   result = PolynomialMultiply(result, result, max);
   if (BigInteger.Compare(n & counter, new BigInteger(0)) != 0)
    result = PolynomialMultiply(result, x, max);
   counter >>= 1;
  }
  return result;
 }
 
 public static void Main(string[] args) {
  try {
   // Get Input
   int n = int.Parse(args[0]);
   BigInteger[] x1 = ExpandReciprocalPowerK(1, n);
   for (int i = 2; i <= n; i++) {
    BigInteger coeff = x1[i];
    x1 = PolynomialMultiply(x1, PolynomialPower(ExpandReciprocalPowerK(i, n), coeff, n), n);
   }

   BigInteger[] x2 = new BigInteger[n + 1], x3 = new BigInteger[n + 1], x4 = new BigInteger[n + 1];
   x3[0] = x2[0] = new BigInteger(1) - x1[0]; 
   x4[0] = new BigInteger(1);
   for (int i = 1; i <= n; i++)
    x4[i] = x3[i] = x2[i] = x1[i];
   for (int i = 2; i <= n; i++) {
    x3 = PolynomialMultiply(x3, x2, n);
    for (int j = 0; j <= n; j++)
     x4[j] += x3[j];
   }
   BigInteger[] x5 = PolynomialMultiply(x1, x4, n);

   Console.WriteLine(x5[n]); // A000137 is not zero-offset
  }
  catch (Exception e) {
   Console.WriteLine(e);
  }
 }

}

Try it online!

Next sequence: A002407, Cuban primes

Second .NET Core C# answer in the first 300 (Since TIO shows both .NET Core and Visual C# Compiler so I assume the two to be different).

Implementation of the algorithm(Mathematica) in the A000137 page in C#, courtesy to Jean-François Alcover (2016).

I tried to find the pattern, but failed to arrive an algorithm that solves it. Used Maclaurin series to calculate the expansion of 1/(1-p(x)) where p is a polynomial of x.

Added some lines so that it points to a nice one

\$\endgroup\$
3
\$\begingroup\$

306. Python 3, 2113 bytes, A000145

def intsqrt(n):
 if n == 0: return 0
 counter, temp = 1, 1
 while counter < n:
  counter <<= 2
  temp <<= 1
 oldtemp1, oldtemp2 = 0, 0
 while oldtemp2 != temp and temp > 0:
  oldtemp2, oldtemp1, temp = oldtemp1, temp, (temp + n // temp) >> 1
 return oldtemp1

def factorial(n):
 if n == 0:
  return 1
 else:
  return n * factorial(n - 1)

def GenerateSquareSequence(n):
 s = 0
 for a in range(intsqrt(n), -1, -1):
  for b in range(min(a, intsqrt(n - a*a)), -1, -1):
   for c in range(min(a, b, intsqrt(n - a*a - b*b)), -1, -1):
    for d in range(min(a, b, c, intsqrt(n - a*a - b*b - c*c)), -1, -1):
     for e in range(min(a, b, c, d, intsqrt(n - a*a - b*b - c*c - d*d)), -1, -1):
      for f in range(min(a, b, c, d, e, intsqrt(n - a*a - b*b - c*c - d*d - e*e)), -1, -1):
       for g in range(min(a, b, c, d, e, f, intsqrt(n - a*a - b*b - c*c - d*d - e*e - f*f)), -1, -1):
        for h in range(min(a, b, c, d, e, f, g, intsqrt(n - a*a - b*b - c*c - d*d - e*e - f*f - g*g)), -1, -1):
         for i in range(min(a, b, c, d, e, f, g, h, intsqrt(n - a*a - b*b - c*c - d*d - e*e - f*f - g*g - h*h)), -1, -1):
          for j in range(min(a, b, c, d, e, f, g, h, i, intsqrt(n - a*a - b*b - c*c - d*d - e*e - f*f - g*g - h*h - i*i)), -1, -1):
           for k in range(min(a, b, c, d, e, f, g, h, i, j, intsqrt(n - a*a - b*b - c*c - d*d - e*e - f*f - g*g - h*h - i*i - j*j)), -1, -1):
            for l in range(min(a, b, c, d, e, f, g, h, i, j, k, intsqrt(n - a*a - b*b - c*c - d*d - e*e - f*f - g*g - h*h - i*i - j*j - k*k)), -1, -1):
             if a*a + b*b + c*c + d*d + e*e + f*f + g*g + h*h + i*i + j*j + k*k + l*l == n:
              t = (a, b, c, d, e, f, g, h, i, j, k, l)
              u = []
              for m in range(0, 4096):
               v = [t[o] * (-1)**(m >> o) for o in range(0, 12)] 
               u.append(repr(sorted(v)))
              w = set(u)
              x = [eval(y) for y in w]
              for z in x:
               p = [z.count(o) for o in set(z)]
               q = 479001600
               for r in p:
                q = q // factorial(r)
               s += q
 return s

Try it online!

Next sequence: A002113: palindromic number

Sorry for the counting by exhaustion algorithm (and the 14-layer for loop), but the sequence also counts representations with negative numbers into the total.

\$\endgroup\$
3
  • \$\begingroup\$ ... and for using Python. \$\endgroup\$
    – DELETE_ME
    Jan 8, 2018 at 5:20
  • \$\begingroup\$ (of course, anyone is free to use any language, just saying) \$\endgroup\$
    – DELETE_ME
    Jan 8, 2018 at 5:27
  • \$\begingroup\$ ... and for CamelCase function name. \$\endgroup\$
    – Maya
    Jan 8, 2018 at 13:53
3
\$\begingroup\$

307. Scratch 2, 6060 bytes, A002113

enter image description here

Try it online!

Next Sequence

Relevant part:

"scripts": [[639, 148.5, [["letter:of:", 1, ["readVariable", "is_palindrome"]]]],
    [683, 370, [["readVariable", "counter"]]],
    [697, 365, [["readVariable", "n"]]],
    [59,
        92,
        [["whenGreenFlag"],
            ["deleteLine:ofList:", "all", "palindromes"],
            ["doAsk", "n: "],
            ["setVar:to:", "n", ["answer"]],
            ["setVar:to:", "counter", 0],
            ["doUntil",
                ["=", ["lineCountOfList:", "palindromes"], ["readVariable", "n"]],
                [["setVar:to:", "is_palindrome", "1"],
                    ["setVar:to:", "i", 0],
                    ["doRepeat",
                        ["stringLength:", ["readVariable", "counter"]],
                        [["doIf",
                                ["not",
                                    ["=",
                                        ["letter:of:", ["+", ["readVariable", "i"], 1], ["readVariable", "counter"]],
                                        ["letter:of:",
                                            ["-", ["stringLength:", ["readVariable", "counter"]], ["readVariable", "i"]],
                                            ["readVariable", "counter"]]]],
                                [["setVar:to:", "is_palindrome", 0]]],
                            ["changeVar:by:", "i", 1]]],
                    ["doIf",
                        ["=", ["readVariable", "is_palindrome"], "1"],
                        [["append:toList:", ["readVariable", "counter"], "palindromes"]]],
                    ["changeVar:by:", "counter", 1]]]]]],

Full code: https://pastebin.com/jEc5W0SL

\$\endgroup\$
4
  • \$\begingroup\$ ... why is this one 1-indexing? \$\endgroup\$
    – DELETE_ME
    Jan 8, 2018 at 8:50
  • \$\begingroup\$ It seems too slow... \$\endgroup\$
    – DELETE_ME
    Jan 8, 2018 at 8:51
  • \$\begingroup\$ Could you make sure the offset is right? For instance, input 0 should give you an output of 0. I can't check this since something's wrong with flash in my browser. (since user202729 seems to be saying something) \$\endgroup\$
    – Maya
    Jan 8, 2018 at 15:13
  • \$\begingroup\$ I've managed to get Flash to work, and this is unfortunately slightly invalid due to the rules about indexing sequences. For example, for all numbers less than 10 the program should output the index. Changing n to n-1 should fix this \$\endgroup\$
    – Maya
    Jan 9, 2018 at 16:00
3
\$\begingroup\$

313. PowerShell, 146 bytes, A001811

function A001811($n){
    [System.Numerics.BigInteger]$a=1;
    for ($i=1; $i -le $n; $i++) {
        $a=$a*($i+4)*($i+4)/$i
    }
    return $a
}

Online test suite

Next sequence: A000146

\$\endgroup\$
3
\$\begingroup\$

322. Mathematica (10.1), 150 bytes, A000249

Symbol[StringJoin[FromCharacterCode[72], FromCharacterCode[101], FromCharacterCode[97], FromCharacterCode[100]]][#(****)&][Round[BesselK[Slot[1], 5]]]

Next sequence

A bit over-the-top due to the character requirement. Effectively the same as Round[#~BesselK~5]&.

\$\endgroup\$
1
  • \$\begingroup\$ I was confused by (****) for a bit, until I remembered that Mathematica comment is (* ... *)... \$\endgroup\$
    – DELETE_ME
    Jan 26, 2018 at 14:24
3
\$\begingroup\$

330. Shakespeare Programming Language, 1854 bytes, A000155

Ye A000155 program.
Ajax, a of n minus four.
Brutus, a of n minus three.
Cicero, a of n minus two.
Dogberry, a of n minus one.
Isabella, input.
Miranda, counter.
Timon, a of n.

Act I: TBD.
Scene I: Taking input.

[Enter Isabella and Timon]

Timon:
       Listen to your heart! Are you worse than the sum of a big old cat and
       a pig?

Isabella:
       If so, you are me.

Timon:
       If so, let us proceed to Act II. Are you as bad as the sum of a furry
       black cat and a pig?

Isabella:
       If so, you are the sum of a beautiful trustworthy handsome pony and a
       coward.

Timon:
       If so, let us proceed to Act II.

[Exeunt Isabella and Timon]
[Enter Brutus and Cicero]

Brutus:
       You are a big chihuahua.

Cicero:
       You are a horse.

[Exeunt Brutus and Cicero]
[Enter Dogberry and Miranda]

Miranda:
       You are the sum of a amazing brave beautiful angel and a hog!

Dogberry:
       You are a pretty cute pony.

[Exit Dogberry]
[Enter Timon]

Scene II: The loop.

Miranda:
       You are the sum of Ajax and the product of a sunny sky and the sum of
       the product of Brutus and the difference between me and the sum of an
       animal and a delicious cow and the product of Dogberry and the sum of
       me and a toad. Am I as big as Isabella?

Timon:
       If so, let us proceed to Scene III.

[Exit Timon]
[Enter Ajax]

Ajax:
       You are the sum of you and a lantern.

Miranda:
       You are Brutus.

[Exeunt Ajax and Miranda]
[Enter Brutus and Cicero]

Cicero:
       You are me.

Brutus:
       You are Dogberry.

[Exeunt Brutus and Cicero]
[Enter Dogberry and Timon]

Timon:
       You are me.

[Exit Dogberry]
[Enter Miranda]

Miranda:
       Let us return to Scene II.

Scene III: TBD.

[Exit Miranda]
[Enter Isabella]

Act II: Finishing up.
Scene I: Output.

Isabella: Open thy heart!
[Exeunt]

Try it online!

Next sequence!

\$\endgroup\$
2
  • \$\begingroup\$ Just when I was almost finished actually implementing the Bessel functions... \$\endgroup\$
    – KSmarts
    Jan 30, 2018 at 15:40
  • \$\begingroup\$ I just realised that I forgot to fill in the act and scene titles... \$\endgroup\$
    – Maya
    Feb 5, 2018 at 14:23
3
\$\begingroup\$

335. Python 2 (Cython), 620 bytes, A000157

from itertools import*
from math import*
from functools import*
n=int(input())+1#offset 1
a=0#answer
for p in permutations(range(n)):
 for i in range(2**n):#inversion
  v=[0]*(2**n)#visited
  c=0#number of cycles
  e=1#all is even
  for x in range(2**n):
   if v[x]:continue
   w=1#1 if this cycle is even
   while 1>v[x]:
    v[x]=1;w^=1
    x=reduce(lambda x,y:x+x+y,[1&(x>>s)for s in p])^i
   e&=w;c+=1
  a+=2**c*(1+e)
print(a//(2**n*factorial(n)*4))

#Come on... it's not that hard.
#Time complexity: 4**n*factorial(n)
#Memory complexity: 2**n
#(which is actually order of magnitude
#faster than the naive algorithm)

Try it online!

Next sequence


Originally intended to work in Python3, but Python 3 (Cython) raises an error "deallocating None".

Sorry for using Python, but programming on mobile is not easy. Posted 2 days ago in chat while waiting for someone else to post, probably with another language.

The next sequence has some chemistry-related things, but the recurrence relation is easy to implement. Ideally I hope someone will explain what the sequence is about. (I don't even explain most of my own answers...)

(Side note: Syntax highlighting fails for some comments)

\$\endgroup\$
4
  • \$\begingroup\$ Well done! You can compute c (and e) without explicitely looking at all possible inputs using linear algebra similar to what I did in answer no. 178 \$\endgroup\$ Feb 17, 2018 at 9:03
  • 2
    \$\begingroup\$ Talking of "what the sequence is about", what's A000157 really? It's obviously not what the title says, but equivalence classes of some kind. \$\endgroup\$ Feb 17, 2018 at 9:17
  • \$\begingroup\$ I actually didn't read the paper, and I think the description of the other sequence is easier to understand, and my first try got it correctly. So I just calculate and halve the other sequence. \$\endgroup\$
    – DELETE_ME
    Feb 17, 2018 at 9:25
  • 1
    \$\begingroup\$ @PeterTaylor After having read 3 papers in the A370 sequence I still can't find any reference to this sequence. No idea. \$\endgroup\$
    – DELETE_ME
    Feb 17, 2018 at 9:44
3
\$\begingroup\$

346. C++14 (gcc), 3780 bytes, A000162

// oeis

#ifndef _GLIBCXX_DEBUG
#define NDEBUG
#endif
#include <cassert>

#include<iostream>
#include<vector>
#include<algorithm>

using v1=std::vector<char>;
using v2=std::vector<v1>;
using v3=std::vector<v2>;

template<class Ar>Ar zip(Ar const& a){
	Ar result(a[0].size());
	for(size_t y=a[0].size();y-->0;){
		result[y].resize(a.size());
		for(size_t x=a.size();x-->0;)
			result[y][x]=a[x][y];
	} return result;
}

template<class Ar>Ar rot1(Ar a){ // rotate cw, assume
	// row-major, row counts down, columns count right
	std::reverse(a.begin(),a.end());
	return zip(a);
}
template<class Ar>Ar rot2(Ar a){ // reverse of rot1
	a=zip(a);std::reverse(a.begin(),a.end());
	return a;
}

template<class Fn>auto each(Fn f){//f must have type (T -> T)
	return [f](auto&& ar){
		for(auto& elem:ar)elem=f(std::move(elem));
		return ar;
	};
}
auto zipeach=each(zip<v2>);

template<class Fn>auto twice(Fn f){//f must have type (T -> T)
	return [f](auto&& ar){
		return f(f(std::forward<decltype(ar)>(ar)));
	};
}

template<class Ar>std::vector<Ar>allrot2(Ar a,std::vector<Ar>& result){
	// calculate all (4) rot of the 2D array (a) and append to (result).
	result.push_back(std::move(a));
	for(int i=3;i-->0;)result.push_back(rot1(result.back()));
	return result;
}
auto rot1each=each(rot1<v2>);

std::vector<v3>allrot(v3 a){
	std::vector<v3>result;
	for(int i=0;i<4;++i){
		/*
		auto r2a=allrot2(a);
		result.insert(result.end(),
			std::make_move_iterator(r2a.begin()),
			std::make_move_iterator(r2a.end()));
		*/
		allrot2(a,result);
		a=rot1each(a);
	}
	a=zipeach(rot1(zipeach(a)));
	allrot2(a,result);
	a=each(twice(rot1<v2>))(a);
	allrot2(a,result);
	return result;
}

void pr(v3 const&a){
	for(v2 const&plane:a){
		for(v1 const&row:plane){
			for(int x:row)std::cout<<x;
			std::cout<<'\n';
		} std::cout<<'\n';
	} std::cout<<"=======\n";
}

// given a v2, return something with its size but all zeroes.
v2 zero(v2 x){x.assign(x.size(),v1(x[0].size())); return x;}
v3 pad (v3 x){// pad left and right with an all-zero v2.
	x.insert(x.begin(),zero(x[0]));//at begin
	x.push_back(x[0]);//at end-now begin is a zero()
	return x;}
v3 trim(v3 x){//the array (x) must not be completely empty
	auto it=x.begin();auto p0=zero(x[0]);
	while(p0==*it)++it;
	x.erase(x.begin(),it);
	while(x.back()==p0)x.pop_back();
	return x;
}

template<class Fn,Fn f>v3 ap3d(v3 a){ // apply for all 3 dimensions
	a=f(a); // x y z -> [x] y z
	a=zipeach(a); // [x] z y
	a=zip(f(zip(a))); // [x] [z] y
	a=zipeach(a); // [x] y [z]
	a=zip(f(zip(a))); // [x] [y] [z]
	return a;
}
auto pad3d =ap3d<decltype(&pad),&pad>;
auto trim3d=ap3d<decltype(&trim),&trim>;

std::vector<v3> expand(std::vector<v3> cubes){
	std::vector<v3> result;
	for(v3&cube:cubes){
		cube = pad3d(std::move(cube));
		size_t const nx=cube.size(),ny=cube[0].size(),nz=cube[0][0].size();
		for(size_t x=nx;x-->0;)
		for(size_t y=ny;y-->0;)
		for(size_t z=nz;z-->0;){
			if(cube[x][y][z])continue;
			if(
				(x&&cube[x-1][y][z])||(x!=nx-1&&cube[x+1][y][z])||
				(y&&cube[x][y-1][z])||(y!=ny-1&&cube[x][y+1][z])||
				(z&&cube[x][y][z-1])||(z!=nz-1&&cube[x][y][z+1])
			){
				result.push_back(cube);
				result.back()[x][y][z]=true;
				result.back()=trim3d(std::move(result.back()));
			}
		}
	}
	return result;
}

int main() {
	std::vector<v3> a={{{{1}}}};
	int n;std::cin>>n;
	++n;//1-based indexing ==> 0-based indexing
	--n;while(n-->0){
		a=expand(a);
		std::sort(a.begin(),a.end());
		a.erase(std::unique(a.begin(),a.end()),a.end());
	}
	long long ans=0;size_t constexpr NCUBEROT=24;
	for(auto&cube:a){
		assert(!cube.empty());
		auto rots=allrot(std::move(cube));
		assert(rots.size()==NCUBEROT);
		++ans;//i==0
		for(size_t i=1;i<NCUBEROT;++i)
			ans+=rots[0]==rots[i];
	}
	assert(ans%NCUBEROT==0);
	std::cout<<ans/NCUBEROT<<'\n';
}

Try it online!

Next sequence. I didn't check what it is, but hopefully easy.

\$\endgroup\$
5
  • \$\begingroup\$ To the next answerer: is the "28-term linear recurrence" proven? If not, you'll need to verify the results up to n=1001, and for that, you need a program that actually computes the sequence. \$\endgroup\$
    – Maya
    Mar 8, 2018 at 17:07
  • \$\begingroup\$ aw, man, the challenge is over :( \$\endgroup\$
    – Giuseppe
    Mar 14, 2018 at 21:17
  • \$\begingroup\$ @NieDzejkob When OEIS has a formula without something like "conjectured" near it, I see no reason to doubt about it. \$\endgroup\$ Mar 15, 2018 at 12:11
  • \$\begingroup\$ @ChristianSievers Well, "gives a 28-term linear recurrence on his web page" is different from a published paper. \$\endgroup\$
    – Maya
    Mar 15, 2018 at 14:25
  • \$\begingroup\$ @NieDzejkob It's from the the person who is the author of everything related to this sequence that is mentioned at the OEIS entry. But yeah, it's not a peer reviewed reult. \$\endgroup\$ Mar 15, 2018 at 22:24
3
\$\begingroup\$

349. Kotlin, 774 bytes, A000607

val primes = mutableListOf<Int>   (2)
val prev   = mutableListOf<Double>(1.0)
fun sequence(n: Int): Double {
    if (n < prev.size)
        return prev.get(n)
    var sum = 0.0
    for (k in (primes.last() + 1)..n) {
        var prime = true
        for (p in primes)
            if (k % p == 0) {
                prime = false
                break
            }
        if (prime)
            primes.add(k)
    }
    for (k in 1..n) {
        var divsum = 0
        for (p in primes) {
            if (p > k)
                break
            if (k % p == 0)
                divsum += p
        }
        sum += divsum * sequence(n - k)
    }
    val res = 1.0 / n * sum
    prev.add(res)
    return res
}
fun main() {
    println(sequence(readLine()!!.toInt()).toInt())
}

Try it online!

Next sequence!

Nothing special here other than caching values because of the immense amount of recursion. (Side note -- this is my first Kotlin program!)

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf, and nice first answer! Just an FYI, your header links to A008472, not A000607 \$\endgroup\$ Apr 13, 2021 at 21:23
  • \$\begingroup\$ @cairdcoinheringaahing Oops, fixed! :p \$\endgroup\$ Apr 13, 2021 at 21:45
3
\$\begingroup\$

86. Gaia, 40 bytes, A000097

1w×ḍΣ¦¦ȯ¦u⟨:l0₁,*¤⟪¤;3<×\?⟫†¦ȯ¦u⟩¦e¦l:!+

Next sequence

\$\endgroup\$
0
3
+100
\$\begingroup\$

363. Iota, 1669 bytes, A000324

***i*i*i*ii***i*i*i*ii***i*i*i*ii***i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii**i*i*ii**i*i*ii**i*i*i*ii*i*i*ii**i*i*ii*i*i*ii**i*i*i*ii*i*i*ii***i*i*i*ii***i*i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii**i*i*i*ii*i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii*i*i*ii*i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii*i*i*ii**i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii*i*i*ii*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii***i*i*i*ii**i*i*ii*i*i*i*ii*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii**i*i*i*ii*i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii*i*i*ii*i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii*i*i*ii**i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii*i*i*ii*i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii**i*i*i*ii*i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii*i*i*ii*i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii*i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii**i*i*ii***i*i*i*ii**i*i*ii**i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii*i*i*ii**i*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii*i*i*ii*i*i*ii**i*i*ii***i*i*i*ii***i*i*i*ii**i*i*ii*i*i*i*ii*i*i*ii***i*i*i*ii***i*i*i*ii**i*i*ii*i*i*i*ii*i*i*ii***i*i*i*ii***i*i*i*ii**i*i*ii*i*i*i*ii*i*i*ii***i*i*i*ii***i*i*i*ii**i*i*ii*i*i*i*ii*i*i*ii***i*i*i*ii*i*i*ii*i*i*ii

Next sequence!

This is a pure lambda calculus function that, given n (0-indexed) as a Church numeral, computes the n-th term of A000324 as another Church numeral. (Also works as a function in Lazy K, which is just a union of multiple minimalist lambda calculus-related languages.)

I don't know of any online system that can test this function directly, but you can test a human-readable version of this program on Ben Lynn's online SK compiler:

true = \x y -> x
false = \x y -> y
is0 = \n -> n (\x -> false) true
n0 = \f x -> x
n1 = \f -> f
n2 = \f x -> f (f x)
n5 = \f x -> f (f (f (f (f x))))
pred = \n f x -> n (\g h -> h (g f)) (\u -> x) (\u -> u)
seq = \x -> is0 x n1 (pred x (\y -> n2 (pred (pred y))) n5)
n3 = \f x -> f (f (f x))
n4 = \f x -> f (f (f (f x)))
main = seq n0  -- try giving n1, n2, n3 instead

The SK compiler's output (without the number argument) was then fed into this Python program to yield the corresponding Iota code.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ :( - I was trying to get Icon to work / understand I \$\endgroup\$
    – emanresu A
    Nov 19, 2021 at 4:21
  • \$\begingroup\$ I actually had an Idris answer too, but I didn't feel like bowling it :P \$\endgroup\$
    – Bubbler
    Nov 19, 2021 at 4:57
3
\$\begingroup\$

369. Add++, 163 bytes, A001015

;you know what is this
`y
;activate y
?^7
;active = ARG to the power of 7
`x
;activate x
oy
;output x!
y:0
;x is 0, why active?
;[X]HTML can't be parsed with regex

Next sequence!

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ @alephalpha fixed, now post \$\endgroup\$
    – Fmbalbuena
    Jan 11, 2022 at 2:05
  • 2
    \$\begingroup\$ Isn't the next OEIS sequence supposed to be the same index as the number of bytes of your code? In this case wouldn't it be A000163, not A049084? \$\endgroup\$
    – Aiden Chow
    Jan 25, 2022 at 7:22
3
\$\begingroup\$

373. Idris, 907 bytes, A000170

-- generate all possible col number lists
powerSet : Nat -> List (List Nat)
powerSet n = index n (iterate (liftA2 (::) (enumFromTo 1 n)) (Nil :: Nil))

-- symmetric difference
symDiff : Nat -> Nat -> Nat
symDiff Z m = m
symDiff (S n) Z = S n
symDiff (S n) (S m) = symDiff n m

-- given a pair of row and col numbers, unless the rows are equal (the same cell),
-- the cols and diagonals must not match
isOKPair : (Nat, Nat) -> (Nat, Nat) -> Bool
isOKPair (i1, n1) (i2, n2) = i1 == i2 || (n1 /= n2 && symDiff n1 n2 /= symDiff i1 i2)

-- attach row numbers to the list of col numbers
enumerate : List Nat -> List (Nat, Nat)
enumerate l = zip (enumFromTo 1 (length l)) l

-- is this board a valid N-Queen solution?
isNQueen : List Nat -> Bool
isNQueen l = all id (liftA2 isOKPair (enumerate l) (enumerate l))

-- count all N-Queen solutions
a000170 : Nat -> Nat
a000170 n = length (filter isNQueen (powerSet n))

Try it online!

Next sequence!

Another I-language into the mix. Idris (especially Idris 1 on TIO) is pretty much Haskell with dependent types and a bit stripped down library. Nat is a Peano natural number type, and all arithmetic functions on Nat are defined recursively by pattern-matching into Z and S n, which is demonstrated in the function symDiff. The other parts of the code just use various Prelude functions to complete the job.

\$\endgroup\$
3
\$\begingroup\$

398. GeoGebra, 176 bytes, A000498

inputVariable = 0
InputBox( inputVariable )
Sum( nCr( inputVariable + 5 , k0 ) * ( -1 ) ^ k0 * ( inputVariable + 1 - k0 ) ^ ( inputVariable + 4 ) , k0 , 0 , inputVariable + 1 )

Takes input through the input box.

Try It On GeoGebra!

Next Sequence!

\$\endgroup\$
4
  • \$\begingroup\$ We don't even got no formula for the next one :/ no idea how to do it \$\endgroup\$
    – naffetS
    Sep 4, 2022 at 2:46
  • \$\begingroup\$ @Steffan well it says in the "Comments" section, Consider the Dirichlet series L_a(s) = sum_{k>=0)} (-a|2k+1) / (2k+1)^s, where (-a|2k+1) is the Jacobi symbol. Then the numbers d_(a,n) are defined by L_a(2n)= (Pi/(2a))^(2n)*sqrt(a)* d_(a,n)/ (2n-1)! for a>1 and n=1,2,3.... So i guess that's technically a formula you can use (except i have absolutely no idea what it means lol)? \$\endgroup\$
    – Aiden Chow
    Sep 4, 2022 at 2:47
  • \$\begingroup\$ that dont make one bit of sense \$\endgroup\$
    – naffetS
    Sep 4, 2022 at 2:48
  • \$\begingroup\$ @Steffan well i just chose the lowest byte count available :| \$\endgroup\$
    – Aiden Chow
    Sep 4, 2022 at 2:48
2
\$\begingroup\$

63. Haxe, 108 bytes, A000057

function(a,n=3){while(a>0){var i=0,x=0,y=1,z;while(y>0&&i++<=n){z=x+y;x=y;y=z%n;}i==n++&&a-->0;}return n-1;}

Test it online!

Next sequence

\$\endgroup\$
2
  • \$\begingroup\$ @geokavel Sorry, I keep forgetting to do that... :P \$\endgroup\$ Jul 22, 2017 at 22:55
  • \$\begingroup\$ Aww crud and I had the Catalan numbers ready for cQuents, but I used it for Fibonacci instead :/ \$\endgroup\$
    – Stephen
    Jul 22, 2017 at 22:58
1
5 6
7
8 9
14

Your Answer

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

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