84
\$\begingroup\$

Fibonacci + FizzBuzz = Fibo Nacci!


Your challenge is to create a Fibo Nacci program!

  • A Fibo Nacci program outputs the first 100 Fibonacci numbers (starting from 1).
  • If the Fibonacci number is divisible by both 2 and 3 (i.e. it is divisible by 6), then output FiboNacci instead of the number.
  • Otherwise, if the Fibonacci number is divisible by 2, then output Fibo instead of the number.
  • Otherwise, if the Fibonacci number is divisible by 3, then output Nacci instead of the number.

Rules

  • The program should take no input.
  • The program should output a new line (\n) after every entry.
  • The program should not print anything to STDERR.
  • The program must output the first 100 Fibo Nacci entries (starting from 1).
  • Standard loopholes are not allowed (by default).
  • This is so shortest code in bytes wins!

Here is the expected output:

1
1
Fibo
Nacci
5
Fibo
13
Nacci
Fibo
55
89
FiboNacci
233
377
Fibo
Nacci
1597
Fibo
4181
Nacci
Fibo
17711
28657
FiboNacci
75025
121393
Fibo
Nacci
514229
Fibo
1346269
Nacci
Fibo
5702887
9227465
FiboNacci
24157817
39088169
Fibo
Nacci
165580141
Fibo
433494437
Nacci
Fibo
1836311903
2971215073
FiboNacci
7778742049
12586269025
Fibo
Nacci
53316291173
Fibo
139583862445
Nacci
Fibo
591286729879
956722026041
FiboNacci
2504730781961
4052739537881
Fibo
Nacci
17167680177565
Fibo
44945570212853
Nacci
Fibo
190392490709135
308061521170129
FiboNacci
806515533049393
1304969544928657
Fibo
Nacci
5527939700884757
Fibo
14472334024676221
Nacci
Fibo
61305790721611591
99194853094755497
FiboNacci
259695496911122585
420196140727489673
Fibo
Nacci
1779979416004714189
Fibo
4660046610375530309
Nacci
Fibo
19740274219868223167
31940434634990099905
FiboNacci
83621143489848422977
135301852344706746049
Fibo
Nacci

The Catalogue

The Snack Stack Snippet at the bottom of this post generates the catalogue 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:

## Language Name, N bytes

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:

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

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:

## Perl, 43 + 2 (-p flag) = 45 bytes

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

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

/* Configuration */

var QUESTION_ID = 63442; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41805; // 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 "http://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 "http://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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\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 = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  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;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) 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);
  }

}
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;
}
<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">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</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>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
15
  • 8
    \$\begingroup\$ What about languages with highest integer type of only 64 bits? :( Isn't 90 fib. numbers enough? \$\endgroup\$
    – Zereges
    Commented Nov 9, 2015 at 18:15
  • 3
    \$\begingroup\$ @Zereges In that matter, I am sorry. :( \$\endgroup\$
    – user41805
    Commented Nov 9, 2015 at 19:30
  • 30
    \$\begingroup\$ Maybe it should be called "Fizzo Nacci" \$\endgroup\$ Commented Nov 9, 2015 at 22:56
  • 4
    \$\begingroup\$ @SztupY Because the output in this question is completely invariant, you don't even need integers at all. Just treat this question as a kolmogorov-complexity question (I even added the tag) and go from there. \$\endgroup\$ Commented Nov 12, 2015 at 17:43
  • 5
    \$\begingroup\$ Math comment: every third Fibonacci number is even, and every fourth Fibonacci number is a multiple of 3. This might lead to alternate coding strategies, which don't require testing divisibility. \$\endgroup\$ Commented Aug 24, 2016 at 18:14

47 Answers 47

50
\$\begingroup\$

Python 2, 62 bytes

a=b=1;exec"print~a%2*'Fibo'+~a%3/2*'Nacci'or a;a,b=b,a+b;"*100

Not much different from the standard FizzBuzz, really.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This is amazing. \$\endgroup\$
    – J Atkin
    Commented Nov 10, 2015 at 18:15
  • \$\begingroup\$ I need to remember this looping construct for my next Ruby golf. This is amazing. \$\endgroup\$
    – clapp
    Commented Nov 16, 2015 at 16:28
23
\$\begingroup\$

C++11 metaprogramming, 348 bytes

#include<iostream>
#define D static const unsigned long long v=
template<int L>struct F{D F<L-1>::v+F<L-2>::v;};template<>struct F<2>{D 1;};template<>struct F<1>{D 1;};template<int Z>struct S:S<Z-1>{S(){auto&s=std::cout;auto l=F<Z>::v;s<<(l%2?"":"Fibo")<<(l%3?"":"Nacci");(l%2&&l%3?s<<l:s)<<"\n";}};template<>struct S<0>{S(){}};int main(){S<100>s;}

Because, why not. It compiles with warning C4307: '+': integral constant overflow, runs fine, but 93+ th Fibonacci numbers are not shown correctly (due to overflow), so this is invalid entry (but I could not win it with that much of bytes though)

Ungolfed

#include <iostream>
#define D static const unsigned long long v = 
template<int L>struct F { D F<L - 1>::v + F<L - 2>::v; };
template<>struct F<2> { D 1; };
template<>struct F<1> { D 1; };

template<int Z>struct S : S<Z - 1>
{
    S()
    {
        auto&s = std::cout;
        auto l = F<Z>::v;
        s << (l % 2 ? "" : "Fibo")
          << (l % 3 ? "" : "Nacci");
        (l % 2 && l % 3 ? s << l : s) << "\n";
    }
};

template<>struct S<0>
{
    S() { }
};

int main()
{
    S<100>s;
}
\$\endgroup\$
6
  • \$\begingroup\$ You could use exploded strings (template <char H, char ...T>) in your templates to (theoretically) handle arbitrary-length values. Then it would just be a matter of examining the last 2 characters in each string to determine divisibility by 2 and/or 3. \$\endgroup\$
    – user45941
    Commented Nov 9, 2015 at 20:23
  • \$\begingroup\$ @Mego I do not understand you. How it would help me to handle values, which do not fit into 64 bits. Also, You need all digits to find out if the number is divisible by 3. \$\endgroup\$
    – Zereges
    Commented Nov 9, 2015 at 21:12
  • \$\begingroup\$ Strings can be arbitrarily long (until you run out of memory). And you're right, I messed up my comment. Still, you could compute the digital sum to determine divisibility by 3. \$\endgroup\$
    – user45941
    Commented Nov 9, 2015 at 21:27
  • \$\begingroup\$ @Mego Implementing addition of those strings would require much more effort. \$\endgroup\$
    – Zereges
    Commented Nov 9, 2015 at 22:17
  • 2
    \$\begingroup\$ You could use the gnu dialect and use __uint128_t, maybe. \$\endgroup\$
    – user16488
    Commented Nov 12, 2015 at 21:54
19
\$\begingroup\$

Pyth, 37 bytes

I loop through the Fibonacci numbers instead of generating them beforehand, since it's really short to do.

K1V100|+*"Fibo"!%=+Z~KZ2*"Nacci"!%Z3Z

Try it online.

\$\endgroup\$
1
  • \$\begingroup\$ Congratulations for winning this challenge! I liked that this solution was fast. \$\endgroup\$
    – user41805
    Commented Nov 15, 2015 at 19:45
14
\$\begingroup\$

Oracle SQL, 212 bytes

Not a golfing language but I had to try...

Concatenating all the rows with \n:

WITH F(R,P,C)AS(SELECT 1,0,1 FROM DUAL UNION ALL SELECT R+1,C,P+C FROM F WHERE R<100)SELECT LISTAGG(NVL(DECODE(MOD(C,2),0,'Fibo')||DECODE(MOD(C,3),0,'Nacci'),''||C),CHR(13))WITHIN GROUP(ORDER BY R)||CHR(13)FROM F

SQLFIDDLE

Or with one entry from the sequence per row (162 bytes):

WITH F(R,P,C)AS(SELECT 1,0,1 FROM DUAL UNION ALL SELECT R+1,C,P+C FROM F WHERE R<100)SELECT NVL(DECODE(MOD(C,2),0,'Fibo')||DECODE(MOD(C,3),0,'Nacci'),''||C)FROM F
\$\endgroup\$
5
  • 3
    \$\begingroup\$ Awesome, just for using SQL \$\endgroup\$ Commented Nov 10, 2015 at 14:23
  • \$\begingroup\$ Just use the last one, since it is the "equivalent" to outputting "per line". And it really is a fine piece of code. Well done! \$\endgroup\$ Commented Nov 11, 2015 at 9:20
  • \$\begingroup\$ @IsmaelMiguel If it's run in SQL*Plus (or another command line interface) then there will be a newline output after each row (as part of how it reports the query output). However, that is a function of the CLI and not the SQL language - to be compliant with the rule The program should output a new line (\n) after every entry I'll leave it as the longer code but the shorter one could be made compliant (without relying on a CLI) by adding ||CHR(13) before the final FROM for 171 chracters. \$\endgroup\$
    – MT0
    Commented Nov 11, 2015 at 10:30
  • \$\begingroup\$ Couldn't you use "\n"? Seems to work on MySQL. (Running select length("\n") returns 1, and running select "\n" doesn't return n, as with select "\p" returns p due to being an invalid escape) \$\endgroup\$ Commented Nov 11, 2015 at 10:33
  • \$\begingroup\$ SELECT LENGTH('\n') FROM DUAL outputs 2 in Oracle as '\n' does not get converted to CHR(13). \$\endgroup\$
    – MT0
    Commented Nov 11, 2015 at 10:43
14
\$\begingroup\$

C#, 175 171 152 145 bytes

class c{static void Main(){for(dynamic a=1m,b=a,c=0;c++<100;b=a+(a=b))System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:"Nacci":"Fibo":"FiboNacci");}}

Uncompressed:

class c {
    static void Main()
    {
        for (dynamic a = 1m, b = a, c = 0; c++ < 100; b = a + (a = b))
            System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:"Nacci":"Fibo":"FiboNacci");
    }
}
\$\endgroup\$
10
  • \$\begingroup\$ Even compressing the output with a DeflateStream the lowest I could get was 191 chars so this is likely very close to the best possible c# answer. A shame BigInteger is required. \$\endgroup\$
    – Jodrell
    Commented Nov 10, 2015 at 10:28
  • \$\begingroup\$ "using System;" will give another -1 in size. \$\endgroup\$
    – olegz
    Commented Nov 10, 2015 at 17:18
  • 1
    \$\begingroup\$ I still had to prefix System.Numerics with System despite the using :-S, so I'm not sure the using will work. \$\endgroup\$
    – Jodrell
    Commented Nov 10, 2015 at 17:22
  • 1
    \$\begingroup\$ You can save 3 characters by replacing the ==0s with >0 and inverting the ternaries: class c{static void Main(){for(System.Numerics.BigInteger a=1,b=1,c=0;c++<100;b=a+(a=b))System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:(object)"Nacci":"Fibo":"FiboNacci");}} \$\endgroup\$
    – Bob
    Commented Nov 11, 2015 at 4:53
  • 3
    \$\begingroup\$ You can save another 7 characters by changing decimal a=1,b=1 to dynamic a=1m,b=a and then you can lose the (object) :) \$\endgroup\$
    – Timwi
    Commented Nov 11, 2015 at 21:58
11
\$\begingroup\$

ShapeScript, 83 bytes

11'1?1?+'77*2**!""'"%r
"@+@0?2%1<"Fibo"*1?3%1<"Nacci"*+0?_0>"@"*!#%'52*0?**!"'"$""~

Try it online!

\$\endgroup\$
4
  • 16
    \$\begingroup\$ Literally looks like my cat jumped on top of my keyboard while I tried to turn on sticky keys. Nice job. \$\endgroup\$
    – jado
    Commented Nov 10, 2015 at 5:38
  • 2
    \$\begingroup\$ @phase figuratively. Either that or you're not looking too closely. Or you have a tiny cat or a giant keyboard. Because this cat managed to type Fibo and Nacci but otherwise avoid all letter keys save for one r. \$\endgroup\$ Commented Nov 10, 2015 at 13:50
  • 3
    \$\begingroup\$ @JanDvorak I think phase has macros setup for that ;) \$\endgroup\$ Commented Nov 10, 2015 at 14:22
  • 2
    \$\begingroup\$ @phase 1. Why is your cat in your room?; 2. why would you want to turn on sticky keys? 3? Why do you not have a cat trap box on your desk to avoid your cat jumping on your keyboard? \$\endgroup\$
    – Nzall
    Commented Nov 11, 2015 at 23:55
8
\$\begingroup\$

Java, 407 398 351 308 bytes

Golfed it with help from @Geobits and @SamYonnou

Spread the word: Verbose == Java

import java.math.*;class A{public static void main(String[]w){BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit(2);for(int i=0;i<100;i++){System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b);c=a;a=b;b=c.add(b);}}}

Ungolfed version:

import java.math.*;

class A
{
  public static void main(String[]w)
  {
    BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit‌​(2);
    for(int i=1;i<=100;i++) {
      System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals‌​(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b);                
      c=a;a=b;b=c.add(b);
    }
  }
}
\$\endgroup\$
10
  • 1
    \$\begingroup\$ This can be golfed more. Import java.math.* instead of the whole thing. Use the constants for ONE and ZERO instead of new BigIntegers. Remove the public from the class. Pack everything except the println statement in the for body inside the loop declaration, etc. I recommend looking over the Java golfing tips in general. \$\endgroup\$
    – Geobits
    Commented Nov 10, 2015 at 16:50
  • \$\begingroup\$ @Geobits Done! 'Twas a pity that I was unfamiliar with BigInteger and its various golfing techniques. \$\endgroup\$
    – Sock
    Commented Nov 10, 2015 at 17:05
  • \$\begingroup\$ Storing BigInteger.ZERO, using flipBit(...) as an alternative to new BigInteger(...), and some other minor things you can get it down to 308: import java.math.*;class A{public static void main(String[]w){BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit(2);for(int i=0;i<100;i++){System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b);c=a;a=b;b=c.add(b);}}} \$\endgroup\$
    – SamYonnou
    Commented Nov 10, 2015 at 17:26
  • \$\begingroup\$ Looks like BigInteger always returns BigInteger.ZERO when some operation like add(...) evaluates to zero so you can use == instead of .equals(z), also you can do away with storing s=t.flipBit‌​(2) (6) and instead do some clever inner assignment like so: import java.math.*;class A{public static void main(String[]w){BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,d,z=a,t=a.flipBit(1),h=t.flipBit(0);for(int i=0;i<100;i++){System.out.println((c=b.mod(t)).add(d=b.mod(h))==z?"FiboNacci":c==z?"Fibo":d==z?"Nacci":b);c=a;a=b;b=c.add(b);}}} these changes get it down to 280 \$\endgroup\$
    – SamYonnou
    Commented Nov 10, 2015 at 18:00
  • 2
    \$\begingroup\$ I think you mean Verbose.isEqualTo(Java) \$\endgroup\$
    – Cyoce
    Commented Aug 24, 2016 at 22:46
8
\$\begingroup\$

Mathematica, 80 bytes

a=b_/;#∣b&;Print/@(Fibonacci@Range@100/.{a@6->FiboNacci,a@2->Fibo,a@3->Nacci})

Adaptation of my older FizzBuzz solution.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ @JacobAkkerboom Sorry, fixed. Also, for versions less than 10.3, replace Echo with Print. \$\endgroup\$ Commented Nov 24, 2015 at 13:31
7
\$\begingroup\$

Ruby, 71 66 bytes

a=b=1;100.times{puts [b,f='Fibo',n='Nacci',f,b,f+n][~b%6];a=b+b=a}

ungolfed:

a = b = 1 #starting values
100.times{
  # create an array, and selects a value depending on the current number
  puts([b, 'Fibo', 'Nacci', 'Fibo', b, 'FiboNacci'][~b%6])
  a=b+b=a # magic
}
\$\endgroup\$
7
  • \$\begingroup\$ I've worked on this for longer than I'd like to admin and can't find any way to improve it. f,n=%w[Fibo Nacci],f,n='Fibbo','Nacci' and f='Fibbo';n='Nacci' all have the same character count. +1 \$\endgroup\$
    – Shelvacu
    Commented Nov 10, 2015 at 22:56
  • 1
    \$\begingroup\$ You can save three bytes by using [b,f='Fibo',n='Nacci',f,b,f+n][~b%6], and two more by removing the parentheses in a=b+b=a. \$\endgroup\$
    – primo
    Commented Nov 14, 2015 at 5:27
  • \$\begingroup\$ Thank you @primo. That is a neat trick with the ~ operator. Never seen it before. And now I know why negative indexes are part of ruby:) \$\endgroup\$
    – MegaTom
    Commented Nov 16, 2015 at 16:28
  • 1
    \$\begingroup\$ Roses are red, Violets are blue, for Haskell and Ruby, I have no clue. \$\endgroup\$ Commented Jun 21, 2016 at 8:22
  • 1
    \$\begingroup\$ I love the symmetry in a=b+b=a \$\endgroup\$
    – Cyoce
    Commented Aug 24, 2016 at 22:48
7
\$\begingroup\$

><>, 116 bytes

01:n1&61>.
ao:@+:v
vv?%2:<
">:3%?vv^16<
o>:3%?!v~v<&
bov"ci"< 6 ;
io"   n  6~?
Focv1&<   o=
"o">+:aa*!o^
>^>"aN"ooo^

Try it online!

\$\endgroup\$
3
  • 6
    \$\begingroup\$ Welcome to the site! :) \$\endgroup\$
    – DJMcMayhem
    Commented Feb 12, 2018 at 20:54
  • \$\begingroup\$ You could probably combine both the 3% sections \$\endgroup\$
    – Jo King
    Commented Feb 13, 2018 at 2:22
  • \$\begingroup\$ @JoKing You'd think so, but they actually lead to different outcomes if n%3!=0. I'm sure there is a way to combine them, but it would mean restructuring the entire program, and I imagine it would actually be longer. \$\endgroup\$
    – hakr14
    Commented Feb 13, 2018 at 2:40
6
\$\begingroup\$

C#, 498 392 320 bytes

I just really wanted to do this with linq, too bad I had to write my own sum function for BigInteger that really killed it :-(

using System.Linq;using System.Numerics;using System.Collections.Generic;static class a{static void Main(){var f=new List<BigInteger>(){1,1};while(f.Count<100)f.Add(f.Skip(f.Count-2).Take(2).Aggregate((a,b)=>b+a));f.ForEach(x=>{System.Console.WriteLine(x%6==0?"FiboNacci":x%2==0?"Fibo":x%3==0?"Nacci":x.ToString());});}}

Ungolfed:

using System.Linq;
using System.Numerics;
using System.Collections.Generic;
static class a
{
    static void Main()
    {
        var f=new List<BigInteger>(){1,1};
        while(f.Count<100)
            f.Add(f.Skip(f.Count-2).Take(2).Aggregate((a,b)=>b+a));
        f.ForEach(x=>
        {
            System.Console.WriteLine(x%6==0?"FiboNacci":x%2==0?"Fibo":x%3==0?"Nacci":x.ToString());
        });
    }
}

Edit: Down to 320 bytes thanks to LegionMammal978 for the aggregate suggestion and thanks to olegz's C# answer for the x%6 shorthand for X%2 && x%3 as well as the use of ternary operators in a single WriteLine statement.

\$\endgroup\$
2
  • 4
    \$\begingroup\$ Have you heard of the Aggregate LINQ function? \$\endgroup\$ Commented Nov 9, 2015 at 22:55
  • \$\begingroup\$ Replace "sum" with "t" to shave 6 bytes. \$\endgroup\$
    – Xantix
    Commented Nov 10, 2015 at 1:42
5
\$\begingroup\$

Pyth, 39

Vtu+Gs>2G99U2|+*!%N2"Fibo"*!%N3"Nacci"N

Very similar to the standard fizzbuzz solution, just with a generator for the Fibonacci numbers.

Try it here

\$\endgroup\$
5
\$\begingroup\$

Python 2, 171 121 bytes

"Brute force approach."

a=[1,1]
print 1
for _ in"q"*99:print[a[1],"Fibo","Nacci","FiboNacci"][a.append(a.pop(0)+a[0])or(1-a[0]%2)+(a[0]%3<1)*2]
\$\endgroup\$
0
4
\$\begingroup\$

Python 2, 100 bytes

x=[1,1]
exec"x+=[x[-1]+x[-2]];"*98
print"\n".join(["Fibo"*(i%2==0)+"Nacci"*(i%3==0)or`i`for i in x])

For the large numbers, adds a L to the end showing it's a long number.

If that's a problem, here is a 104 byte solution

x=[1,1]
exec"x+=[x[-1]+x[-2]];"*98
print"\n".join(["Fibo"*(i%2==0)+"Nacci"*(i%3==0)or str(i)for i in x])
\$\endgroup\$
2
  • \$\begingroup\$ You can shorten the for loop using this tip: codegolf.stackexchange.com/a/5047/42736. In particular the exec tip looks good. \$\endgroup\$
    – J Atkin
    Commented Nov 9, 2015 at 19:19
  • \$\begingroup\$ +1 for the exec <program_string>*n trick. Nice! \$\endgroup\$
    – agtoever
    Commented Nov 10, 2015 at 9:01
4
\$\begingroup\$

Javascript, 93 90 86 84 Bytes

for(a=0,b=1,i=100;i--;a=[b,b+=a][0])console.log((b%2?'':'Fibo')+(b%3?'':'Nacci')||b)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could save four bytes by changing a=[b,b=a+b][0] to b=a+b,a=b-a. Also, in a completely unrelated note, I like the way you answer like really fast in Stack Overflow hehe Have a nice day \$\endgroup\$
    – Piyin
    Commented Nov 2, 2017 at 22:22
2
\$\begingroup\$

Javascript(ES6), 137 134 bytes

g=x=>(a=[1,1],f=(x)=>(a[x]=y=a[x-1]+a[x-2],(y%2&&y%3?y:(!(y%2)?'Fibo':'')+(!(y%3)?'Nacci':''))+'\n'+((++x<99)?f(x):'')),'1\n1\n'+f(2))

Recursive function that calculates fibonnacci, put it in an array then output Fibo,Nacci or the number and call itself to calculate next until 100.

It breaks at 73 because of javascript Number precision. Only way to get around that would be to add my own bit calculation.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This doesn't work, it goes wrong after 5527939700884757 + 8944394323791464 = 14472334024676220 when it should be 14472334024676221 because JavaScript uses 16 bit precision floats and that requires 17 bits of precision. You should also print 1 twice. \$\endgroup\$ Commented Nov 10, 2015 at 17:31
  • \$\begingroup\$ Added the print 1 twice. For the precision, I need to change everythin on the code to make it work (not using Number but Uint32Array and doing computation bits by bits) \$\endgroup\$
    – Naouak
    Commented Nov 10, 2015 at 22:18
2
\$\begingroup\$

dc, 100 89 79 bytes

[sG[]]sx[dn]s01df[sbdlb+lbrdd2%d[Fibo]r0!=xnr3%d[Nacci]r0!=xn*0!=0APzZ3>o]dsox

Inspired by http://c2.com/cgi/wiki?DeeCee

\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Programming Puzzles & Code Golf! \$\endgroup\$
    – Dennis
    Commented Nov 12, 2015 at 18:05
2
\$\begingroup\$

Wolfram Language, 84 bytes

Kind of cheating of course, because of the built in Fibonacci.

t=Fibonacci@Range@100;g=(t[[#;;;;#]]=#2)&;g[3,Fibo]g[4,Nacci]g[12,FiboNacci]Print/@t

Example command to run the script

/Applications/Mathematica.app/Contents/MacOS/WolframKernel -script ~/Desktop/fibo.wl
\$\endgroup\$
2
\$\begingroup\$

Perl, 74 bytes

map{print+(Fibo)[$_%2].(Nacci)[$_%3]||$_ for$a+=$b||1,$b+=$a}1..50

Requires the following command line option: -lMbigint, counted as 8.


Sample Usage

$ perl -lMbigint fibo-nacci.pl

Perl, 79 bytes

use bigint;map{print+(Fibo)[$_%2].(Nacci)[$_%3]||$_,$/for$a+=$b||1,$b+=$a}1..50

Same as above, without requiring any command line options.

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

GolfScript, 47 bytes

100,{1.@{.@+}*;..2%!'Fibo'*\3%!'Nacci'*+\or}%n*

Explanation

100,            # push 0..99
{               # map
  1.@           # push 1 twice, rotate counting var to the top
  {             # apply that many times
    .@+         # copy the top, rotate and add
                # if the stack is [a b], this produces: [a b b] -> [b b a] -> [b b+a]
  }*
  ;..           # discard the top, duplicate twice
  2%!'Fibo'*\   # divisible by 2 ? 'Fibo' : ''
  3%!'Nacci'*   # divisible by 3 ? 'Nacci' : ''
  +\or          # concatenate, if empty use the numeric value instead
}%
n*              # join all with a newline
\$\endgroup\$
2
\$\begingroup\$

PARI/GP, 76 73 bytes

Saved three bytes courtesy of Mitch Schwartz.

for(n=b=!a=1,99,b=a+a=b;print(if(b%2,"",Fibo)if(b%3,if(b%2,b,""),Nacci)))

Sample Usage

$ gp -qf < fibo-nacci.gp
\$\endgroup\$
2
  • 1
    \$\begingroup\$ It's shorter not to use built-in; I got 73 with for(i=b=!a=1,99,b=a+a=b; ... \$\endgroup\$ Commented Nov 14, 2015 at 18:39
  • 1
    \$\begingroup\$ @MitchSchwartz it used to be called fibo ;) \$\endgroup\$
    – primo
    Commented Nov 14, 2015 at 23:12
2
\$\begingroup\$

><>, 128 119 bytes

111&v       >:3%0=?v>  v
?;ao>:2%0=?v :3%0=?v :n>:}+&:1+&aa*=
            ^oooo < ^ooooo <
           >"obiF"^>"iccaN"^

I shamelessly stole borrowed an existing program FizzBuzz program and modified it to work for the Fibo Nacci sequence. It outputs numbers forever. Now it is fixed, i.e. it only outputs 100 numbers. Try it here.

\$\endgroup\$
3
  • 2
    \$\begingroup\$ You must only output the first 100 Fibo Nacci numbers, no more, no less. \$\endgroup\$
    – user41805
    Commented Nov 11, 2015 at 5:31
  • \$\begingroup\$ @ΚριτικσιΛίθος I finally got around to making it only output 100 numbers. \$\endgroup\$
    – DanTheMan
    Commented Nov 18, 2015 at 16:52
  • \$\begingroup\$ This outputs 101 numbers on TIO but doesn't work at the linked site \$\endgroup\$
    – Jo King
    Commented Feb 13, 2018 at 4:10
2
\$\begingroup\$

05AB1E, 29 bytes

тENÅfDÑ23SÃvá.•iÑ+FÌ;•™#yèJ},

Inspired by @Grimmy's bottom answer of the 1, 2, Fizz, 4, Buzz challenge (doesn't work in the legacy version with S removed, because there is a bug in the compressed string .•iÑ+FÌ;•; the compiler probably thinks there is an open if/loop block due to the i/F..).

Try it online.

Explanation:

тE                # Loop `N` in the range [1,100]:
  NÅf             #  Get the N'th Fibonacci number
     D            #  Duplicate it
      Ñ           #  Pop this copy, and push a list of its divisors
       23SÃ       #  Only keep the divisors [2,3]
 v                #  Inner loop over those remaining divisors (or not if none are left):
  á               #   Only leave the letters of the current top of the stack
                  #   (to get rid of the Fibonacci number that was still on the stack)
   .•iÑ+FÌ;•      #   Push compressed string "fibo nacci"
            ™     #   Titlecase each: "Fibo Nacci"
             #    #   Split it on spaces: ["Fibo","Nacci"]
              yè  #   Index the current divisor `y` into it (0-based and with wraparound,
                  #   so 2 will index into "Fibo" and 3 into "Nacci")
                J #   Join everything on the stack together
 },               #  After the inner loop: pop and print the top with trailing newline

See this 05AB1E tip of mine (section How to compress strings not part of the dictionary?) to understand why .•iÑ+FÌ;• is "fibo nacci".

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

Vyxal j, 21 bytes

ÞF₁Ẏƛ₍₂₃«-∇j€₌p«⌈ǐ*∑∴

Try it Online!

Basically the same as the standard 11 byte FizzBuzz with a few changes

Explained

ÞF₁Ẏƛ₍₂₃«-∇j€₌p«⌈ǐ*∑∴
ÞF₁Ẏ                  # The first 100 fibonacci numbers
    ƛ                 # to each item n:
     ₍₂₃              #   push a list [n % 2 == 0, n % 3 == 0]
        «-∇j€₌p«      #   push the string "fibo nacci"
                ⌈ǐ    #   split on spaces and titlecase each
                  *∑  #   vectorised string multiply and sum - this is like writing way of writing ("Fibo" * (n % 2 == 0) + "Naci" * (n % 3 == 0))
                    ∴ #   choose the greatest of n and that string. A number will always be greater than an empty string, and a non-empty string will always be greater than a number
                      # Just like the standard fizzbuzz, the `j` flag joins on newlines
\$\endgroup\$
1
\$\begingroup\$

Pyth, 51 bytes

V.Wn100lHaZ+@Z_1@Z_2[1 1)|+*"Fibo"}2JPN*"Nacci"}3JN

Generates the Fibonacci sequence then decides what to print.

                    [1 1)                           - H = [1,1]
  Wn100lH                                           - While len(H)!=100 
         aZ+@Z_1@Z_2                                - H.append(H[-1]+H[-2])
V.                                                  - For N in H:
                                    JPN             - Set J to the prime factorization of H
                           *"Fibo"}2J               - If there is a 2 in the factorization, add "Fibo" to a string
                                       *"Nacci"}3J  - If there is a 3 in the factorization, add "Nacci" to a string
                          +                         - Join them together
                         |                        N - If the string isn't empty (If it isn't divisible by 2 or 3), print N
                                                    - Else print the string

To test, try this (only does the first 20 numbers)

V.Wn20lHaZ+@Z_1@Z_2[1 1)|+*"Fibo"}2JPN*"Nacci"}3JN
\$\endgroup\$
2
  • \$\begingroup\$ How long does it take to run the actual program? \$\endgroup\$
    – user41805
    Commented Nov 9, 2015 at 17:45
  • \$\begingroup\$ I have no idea, it didn't in the 30 seconds it took to work out that working out such large prime factorizations would probably slow it down a lot. \$\endgroup\$
    – Blue
    Commented Nov 9, 2015 at 17:46
1
\$\begingroup\$

Clojure, 127 bytes

(def f(lazy-cat[1 1](map +' f(rest f))))(doseq[x(take 100 f)](println(str(if(even? x)'Fibo)({0'Nacci}(mod x 3)(if(odd? x)x)))))

Ungolfed:

(def fib (lazy-cat [1 1] (map +' fib (rest fib))))

(doseq [x (take 100 fib)]
  (println (str (if (even? x) 'Fibo)
                ({0 'Nacci}
                 (mod x 3)
                 (if (odd? x) x)))))

Some tricks used:

  • That pretty little def that gives the Fibonacci sequence itself is stolen shamelessly from Konrad Garus.
  • str can take symbols as input. Crazy, right?
  • Maps and default values are the shortest way to write if in some cases.
\$\endgroup\$
4
  • \$\begingroup\$ What is lazy-cat? \$\endgroup\$
    – user41805
    Commented Nov 10, 2015 at 5:02
  • \$\begingroup\$ @ΚριτικσιΛίθος It lazily concatenates multiple sequences. In this case, it concatenates the first two elements of the Fibonacci sequence ([1 1]) with the result of summing each element in the Fibonacci sequence with the element following it. \$\endgroup\$
    – Sam Estep
    Commented Nov 10, 2015 at 11:54
  • \$\begingroup\$ Am I right in guessing that this is basically the Clojure version of fibs = 0 : 1 : zipWith (+) fibs (tail fibs)? \$\endgroup\$ Commented Nov 10, 2015 at 13:09
  • \$\begingroup\$ @SohamChowdhury Yes, as far as I can tell. \$\endgroup\$
    – Sam Estep
    Commented Nov 10, 2015 at 13:14
1
\$\begingroup\$

CJam, 44 bytes

XX{_2$+}98*]{_B4bf%:!"Fibo Nacci"S/.*s\e|N}/

Try it online in the CJam interpreter.

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

QBasic, 144 141 bytes

Not particularly small, but it beats C++ and C#

r=1:FOR i=1 TO 046:a$="":q=p+r
IF q MOD 2=0 THEN a$="Fibo"
IF q MOD 3=0 THEN a$=a$+"Nacci"
IF a$="" THEN a$=STR$(q)
PRINT a$:r=p:p=q:NEXT

No declarations, used the : wherever possible because it's 1 byte cheaper than CRLF. Prefixed a 0 to the loop counter: Basic will overflow on the 47th Fibonacci character, so compensated for the extra byte that should be there.

EDIT: Neil saved me 3 bytes: 141 bytes.

\$\endgroup\$
1
  • \$\begingroup\$ You can remove the first a$+ since it's known to be the empty string at this point. \$\endgroup\$
    – Neil
    Commented Nov 11, 2015 at 8:40
1
\$\begingroup\$

F#, 202 163 149 bytes

Seq.unfold(fun(a,b)->printfn"%s"(a%6m|>function|0m->"FiboNacci"|2m|4m->"Fibo"|3m->"Nacci"|_->string a);Some(1,(b,a+b)))(1m,1m)|>Seq.take 100|>Seq.sum

This is an FSX (F# script) file

\$\endgroup\$
1
  • \$\begingroup\$ I am surprised that this works \$\endgroup\$
    – asibahi
    Commented Aug 24, 2016 at 19:35
1
\$\begingroup\$

PHP, 75 bytes

<?for(;4e20>$b=bcadd($a,$a=$b)?:1;)echo[Fibo][++$i%3].[Nacci][$i%4]?:$b,~õ;

Surpisingly competitive. Requres PHP v5.5 or higher. I assume default settings, as they are without an .ini (you may disable your local .ini with the -n option).


Sample Usage

$ php -n fibo-nacci.php
\$\endgroup\$
2
  • \$\begingroup\$ WIth -n bcadd doesn't work even when bcmath is installed. Without -n lots of stuff is output on stderr. \$\endgroup\$
    – Sylwester
    Commented Feb 12, 2018 at 21:10
  • \$\begingroup\$ Works on my box(es). \$\endgroup\$
    – primo
    Commented Feb 13, 2018 at 8:35

Your Answer

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

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