90
votes
\$\begingroup\$

4, 8, 15, 16, 23, 42

Write a program that outputs this sequence of numbers infinitely. However, The Numbers must not appear in your source code anywhere.

The following is not a valid Java program to output The Numbers because The Numbers appear in its source code:

class TheNumbers {
    public static void main(String[] args) {
        for(int n = 0;;) System.out.println(
            n == 4 ? n = 8 :
            n == 8 ? n = 15 :
            n == 15 ? n = 16 :
            n == 16 ? n = 23 :
            n == 23 ? n = 42 : (n = 4)
        );
    }
}

The definition of "The Numbers must not appear in your source code" is as follows:

  • You must not use the numeral 4.
  • You must not use the numeral 8.
  • You must not use the numeral 1 followed by the numeral 5.
  • You must not use the numeral 1 followed by the numeral 6.
  • You must not use the numeral 2 followed by the numeral 3.

If your language ignores certain characters that can be placed between the numerals, it's not a valid substitution. So for example if your language interprets the literal 1_5 as 15, this would count as the numeral 1 followed by the numeral 5.

Alternative bases are included in the restriction, so for example:

  • Binary 100 can't be used as a substitute for 4.
  • Octal 10 can't be used as a substitute for 8.
  • Hexadecimal F can't be used as a substitute for 15.

Therefore, the following is a valid (but not very inspired) Java program to output The Numbers because The Numbers do not appear in its source code:

class TheNumbers {
    public static void main(String[] args) {
        for(int n = '*';;) {
            System.out.println(n -= '&');
            System.out.println(n *= 2);
            System.out.println(n += 7);
            System.out.println(++n);
            System.out.println(n += 7);
            System.out.println(n += 19);
        }
    }
}

Note that in that program, '*' and '&' are substituted for the integers 42 and 38, because otherwise the numerals 4 and 8 would appear in its source code.

The definition of "outputs the sequence infinitely" is open to interpretation. So, for example, a program that outputs glyphs getting smaller until they are "infinitely" small would be valid.

Kudos if you are able to generate the sequence in some way that's not basically hard-coding each number.

This is a popularity contest, so be creative. The answer with the most up votes on March 26th is the winner.

\$\endgroup\$

closed as too broad by Alex A. Apr 23 '16 at 0:25

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

locked by Alex A. Apr 23 '16 at 0:25

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. See the help center for guidance on writing a good question.

Read more about locked posts here.

  • 8
    \$\begingroup\$ I can count 6 downvotes but no comments :/ \$\endgroup\$ – Vereos Mar 12 '14 at 13:52
  • 11
    \$\begingroup\$ @Vereos, "This is a stupid question" isn't very constructive, which might be why no-one posted it as a comment. \$\endgroup\$ – Peter Taylor Mar 12 '14 at 15:26
  • 18
    \$\begingroup\$ There are 11 types of people in this world: those that watched Lost, those that didn't, and those that don't understand binary. \$\endgroup\$ – squeamish ossifrage Mar 12 '14 at 16:26
  • 7
    \$\begingroup\$ @PeterTaylor For sure, but newcomers mostly will not get that and leave the site instead of trying to improve their future questions. I guess that This isn't an interesting question, IMHO, since the solution is pretty trivial. Please post in the sandbox next time. would be way better than This is a stupid question., but that's just my personal opinion. \$\endgroup\$ – Vereos Mar 12 '14 at 16:57
  • 3
    \$\begingroup\$ I notice the question does not prohibit outputting other numbers. So at least according to infinite-monkey-theory an unadulterated pseudo-random number generator should do the trick. \$\endgroup\$ – kojiro Mar 13 '14 at 13:21

109 Answers 109

3
votes
\$\begingroup\$

Java

Here is a very straightforward icebreaker entry which does a little more than the 'bare-minimum' example in the OP.

The Numbers

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class TheNumbers {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JFrame() {
                    JLabel lbl = new JLabel("00", JLabel.CENTER);
                    int[] nums;
                    int i;
                    {
                        int n = '$' & '^';
                        nums = new int[] {
                            n,
                            n *= 2,
                            n += 7,
                            ++n,
                            n += 7,
                            n += 19,
                        };
                        lbl.setFont(lbl.getFont().deriveFont(63f));
                        lbl.setOpaque(true);
                        lbl.setBackground(Color.BLACK);
                        lbl.setForeground(Color.WHITE);
                        add(lbl);
                        pack();
                        setResizable(false);
                        setLocationRelativeTo(null);
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        lbl.setText(Integer.toString(nums[0]));
                        new Timer(500, new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent ae) {
                                lbl.setText(Integer.toString(nums[i = (i + 1) % 6]));
                                validate();
                            }
                        }).start();
                    }
                }.setVisible(true);
            }
        });
    }
}
\$\endgroup\$
  • \$\begingroup\$ Dat Swing... Why do you put code in an inner JFrame class? Why not extend JFrame or create an object and call methods on it? \$\endgroup\$ – nrubin29 Mar 12 '14 at 23:33
  • 1
    \$\begingroup\$ @nrubin29 Just to amuse myself. \$\endgroup\$ – Radiodef Mar 12 '14 at 23:34
  • 1
    \$\begingroup\$ Alright, fair enough. \$\endgroup\$ – nrubin29 Mar 12 '14 at 23:54
  • \$\begingroup\$ Would the animated gif itself not count as an entry? It's a program, too. \$\endgroup\$ – kojiro Mar 13 '14 at 13:20
1
vote
\$\begingroup\$

Python

def main():
    a = range(3+1)
    b = range(7+1)
    c = range(3*5)
    d = range(13+3)
    e = range(20+3)
    f = range(6*7)
    All = [a,b,c,d,e,f]
    while True:
        for n in All:
            print(len(n))
main()
\$\endgroup\$
  • \$\begingroup\$ Thanks for the edit, I didn't think that could also work! \$\endgroup\$ – Ol' Reliable Mar 12 '14 at 17:47
25
votes
\$\begingroup\$

D

Not allowed to use the numbers 4, 8, 15, 16, 23, or 42 in my code? No problem, then I won't use numbers at all!

import std.stdio;

void main()
{
    while( true )
    {
        ( ',' - '('  ).writeln;
        ( '/' - '\'' ).writeln;
        ( '/' - ' '  ).writeln;
        ( '_' - 'O'  ).writeln;
        ( '^' - 'G'  ).writeln;
        ( '~' - 'T'  ).writeln;
    }
}
\$\endgroup\$
  • 6
    \$\begingroup\$ ASCII arithmetic is best arithmetic. \$\endgroup\$ – Pharap Mar 15 '14 at 17:42
  • 2
    \$\begingroup\$ So after C, came a language called D? \$\endgroup\$ – cegprakash Mar 20 '14 at 9:01
  • \$\begingroup\$ @cegprakash And before C was B \$\endgroup\$ – SirPython Apr 9 '15 at 0:33
11
votes
\$\begingroup\$

JavaScript

No numbers at all is a good move. But rather than print the sequence once per pass through the loop, only print once number per pass.

t = "....A...B......CD......E..................FEDCBA";
b = k = --t.length;
do {
    console.log(p = t.indexOf(t[k]));
} while (k-=!!(p-k)||(k-b));

The lower part of the string codes the numbers to print and the upper part of the string codes the next character to find. Where the two parts meet (a single F) codes resetting the cycle.

\$\endgroup\$
20
votes
\$\begingroup\$

Haskell, 1 LoC

import Data.Char; main = putStr $ unwords $ map (show . (+)(-ord 'D') . ord) $ cycle "HLST[n" 

I've decided to go for a readable one-liner just to show how awesome Haskell is. Also, I've decided to avoid all digits, just in case.

Thanks to built-in lazy evaluation, Haskell can manipulate (map, split, join, filter...) infinitely long lists just fine. It even has multiple built-ins to create them. Since a string is just a list of characters, infinitely long strings are no mystery to Haskell either.

\$\endgroup\$
  • 2
    \$\begingroup\$ I love the way Haskell and the like do functional programming :D \$\endgroup\$ – Jwosty Mar 12 '14 at 12:14
  • 2
    \$\begingroup\$ fromEnum looks nicer than Data.Char.ord, and is somewhat shorter \$\endgroup\$ – mniip Mar 12 '14 at 13:43
  • 1
    \$\begingroup\$ Whuh ... how? Could you explain? \$\endgroup\$ – Pureferret Mar 13 '14 at 14:57
  • 1
    \$\begingroup\$ I just noticed the innocuous characters right at the end. I assume the have something to do with it? \$\endgroup\$ – Pureferret Mar 13 '14 at 17:01
  • 1
    \$\begingroup\$ Ah. Yes, indeed, they do. \$\endgroup\$ – John Dvorak Mar 13 '14 at 17:20
6
votes
\$\begingroup\$

Emacs Lisp 73 chars

The best way to loop forever? A cyclic list!

(let((a'(?\^D?\^H?\^O?\^P?\^W?*)))(setcdr(last a)a)(while(print(pop a))))

But wait, there's more!

?\^D is the nice way to insert the char for EOT, however if I was just submitting a file I wouldn't need the literal "\^D" I could just insert a '?' followed by an actual EOT character, thus taking the real number of needed chars down to: 63

Edit

I've been working on "gel" which is not a real language yet, but is basically series of emacs lisp macros for code golf. In "gel" this would be the solution:

(m a(~o ?\^D?\^H?\^O?\^P?\^W?*)(@(<^(^ a))(...)))

and without the waiting:

(m a(~o ?\^D?\^H?\^O?\^P?\^W?*)(@(<^(^ a))))

44 chars with nice character entry. Would be 34 if not for it being a web submission.

\$\endgroup\$
18
votes
\$\begingroup\$

Java

I can't find a pattern in that sequence. If there's no recognizable pattern, we might as well just throw a bunch of small primes together, cram them into Java's built-in RNG, and call it a day. I don't see how that could possibly go wrong, but then again, I'm an optimist :)

import java.util.Random;
public class LostNumbers {
    public static void main(String[] args) {
        long nut=2*((2*5*7)+1)*((2*2*3*((2*2*2*2*11)+3))+5)*
                   ((3*5*((2*3*3)+1)*((2*2*2*2*2*3)+1))+2L);
        int burner=2*2*2*5;
        while(true){
            Random dice = new Random(nut);
            for(int i=0;i<6;i++)
                System.out.print((dice.nextInt(burner)+3) + " "); // cross your fingers!
            System.out.println();
        }
    }
}
\$\endgroup\$
77
votes
\$\begingroup\$

Perl

There is nothing hidden in the source code. Nope. If the code doesn't work, type use re "eval"; before it (required in Perl 5.18).

''=~('('.'?'.('{').(
'`'|'%').('['^'-').(
"\`"| '!').('`'|',')
.'"'. '\\' .'@'.('`'
|'.') .'=' .'('.('^'
^('`'       |"\*")).
','.("\:"& '=').','.
('^'^('`'| ('/'))).(
'^'^("\`"| '+')).','
.('^'^('`'|('/'))).(
'^'^('`'|'(')).','.(
'^'^('`'|',')).('^'^
("\`"|     '-')).','
.('^' ^('`' |'*')).(
'^'^( "\`"| (','))).
(')').     ';'.('['^
','). ('`'| ('(')).(
"\`"| ')'). ('`'|','
).('`'     |'%').'('
.'\\'.'$'.'|'."\=".(
'^'^('`'|'/'))."\)".
'\\'.'{'.'\\'."\$".(
"\["^ '/')       .((
'=')  ).+( '^'^('`'|
'.' ) ).(( (';'))).(
"\`"| '&').     ('`'
|'/') .('['^')') .((
'(')) .''. '\\'. '@'
.+(     '`'     |'.'
).')'.'\\'.'{'.('['^
'(').('`'|',').('`'|
'%').('`'|'%').('['^
'+'). '\\'.     '$'.
'_'.  '-'. '\\'. '$'
.+( ( '[') ^'/').';'
.'\\' .'$'      .''.
('['^ '/') .'='. (((
'\\') )).+ "\$". '_'
.((     ';'     )).+
'\\'.'$'.'_'.'='.'='
.('^'^('`'|'*')).'|'
.'|'.('['^'+').('['^
')'     ).(     '`'|
(( ')')) ) .('`' |((
'.'))).( '['^'/' ).+
(((     (((     '\\'
)) )))).'"'.('{' ^((
(( '[')))) ).''. (((
((       ((     '\\'
))))))).'"'.';'.('['
^'+').('['^')').('`'
|')').('`'|'.').('['
^+ '/').''.     '\\'
.+ '}'. +( "\["^ '+'
). ('[' ^"\)").( '`'
|+       ((     ')')
)).('`' |+ '.').('['
^'/').( (( '{'))^'['
).'\\'. ((       '"'
)).('!'^'+').('\\').
'"'.'\\'.'}'.(('!')^
'+').'"'.'}'.')');$:
='.'#madebyxfix#'.'=
^'~';$~='@'|"\(";#;#

Explanation in spoiler.

This is a simple Perl program which makes use of multiple bitwise operations, and evaluates the regular expression using =~ operator. The regex begins with (?{ and ends with }). In Perl, this runs code while evaluating regular expression - this lets me use eval without actually using it. Normally, however, re "eval" is required, for security reasons, when evaluating regular expressions from strings (some older programs actually took regular expressions from the user) - but it turns out that before Perl 5.18 there was a bug causing constant folded expressions to work even without this pragma - if you are using Perl 5.18, type use re "eval"; before the code to make it work. Other than that, there is not much else to this code.

\$\endgroup\$
  • 9
    \$\begingroup\$ I'm starting to look like this but I still don't see it.. \$\endgroup\$ – rdurand Mar 12 '14 at 16:55
  • 69
    \$\begingroup\$ @xfix "This is a simple Perl program" - if that's the case, I'd hate to see a complicated one. \$\endgroup\$ – MikeTheLiar Mar 12 '14 at 19:24
  • 8
    \$\begingroup\$ Hey look, it's a schooner. \$\endgroup\$ – roippi Mar 12 '14 at 20:31
  • 5
    \$\begingroup\$ @roippi Haha, you dumb bastard. It's not a schooner, it's a SAILBOAT! \$\endgroup\$ – MikeTheLiar Mar 13 '14 at 14:52
  • 7
    \$\begingroup\$ Protip: copy/paste to Notepad++ and zoom all the way out. \$\endgroup\$ – MikeTheLiar Mar 14 '14 at 18:59
4
votes
\$\begingroup\$

My first participation on CodeGolf.SE :

Objective-C (polynomial version)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        for (int i = 1; ; i++) {
            NSLog(@"%.0f", (1200*2 - (9792/2)*i + 3670*pow(i,2) - 1175*pow(i,3) + 170*pow(i,3)*i - 9*pow(i,5)) / (20*2));
            if (i==6) i=0;
        }
    }
    return 0;
}

Polynomial used :

       2400 - 4896 * i + 3670 * i^2 - 1175 * i^3 + 170 * i^4 - 9 * i^5 
f(i) = ---------------------------------------------------------------
                                     40

Which gives the expected values for i in [1,6].

Objective-C (binary version)

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        while (YES) {
            NSLog(@"%i", 32 >> 3);
            NSLog(@"%i", 32 >> 2);
            NSLog(@"%i", 30 >> 1);
            NSLog(@"%i", 32 >> 1);
            NSLog(@"%i", 92 >> 2);
            NSLog(@"%i", 336 >> 3);
        }
    }
    return 0;
}
\$\endgroup\$
  • \$\begingroup\$ Does this output the number infinitely? Also, you are typically supposed to provide the full program or function when solving challenges. \$\endgroup\$ – Hosch250 Mar 12 '14 at 16:19
  • \$\begingroup\$ Yes, it does print infinitely beacause of the never-ending for loop. I updated the code with more context, I thought just the "interesting part" was enough :) \$\endgroup\$ – rdurand Mar 12 '14 at 16:30
10
votes
\$\begingroup\$

Ruby

Generates the Numbers by embedding the equally mystical sequence 0, ∞, 9, 0, 36, 6, 6, 63;
No good can come from this.

(0..1/0.0).each{|i|puts"kw9ygp0".to_i(36)>>i%6*6&63}
\$\endgroup\$
  • \$\begingroup\$ All ruby code looks like it should just error and die; it shocks me to this day that any of it runs at all! \$\endgroup\$ – alexandercannon Mar 21 '14 at 15:35
10
votes
\$\begingroup\$

C (54 50 chars)

I'm posting a golf answer because golfing at least makes it fun.

main(a){while(printf("%d\n","gAELMT"[a++%6]-61));}
\$\endgroup\$
  • \$\begingroup\$ If you're golfing, you could (arguably) drop the a=0;. The only effect would be that you may start the sequence somewhere other than 4 (probably 8). Anyway, this will mess up the sequence when a overflows. It's technically undefined behavior, but the likely result is that you'll print garbage half the time. \$\endgroup\$ – jerry Mar 13 '14 at 17:25
  • \$\begingroup\$ Or just cycle the string to "gAELMT" :) \$\endgroup\$ – orion Mar 13 '14 at 18:53
  • \$\begingroup\$ Sure, unless someone invokes your program with arguments :) Still printing garbage half the time, though. \$\endgroup\$ – jerry Mar 14 '14 at 0:56
  • 3
    \$\begingroup\$ If you give arguments to a program that doesn't need any, you pay the price :) \$\endgroup\$ – orion Mar 14 '14 at 9:42
  • 1
    \$\begingroup\$ for doesn't help if there's no initialization. for(;;) is the same number of characters as while(). I interpreted the rules so that newlines have to be there... But I could use tail recursion with main... \$\endgroup\$ – orion Mar 20 '14 at 14:36
2
votes
\$\begingroup\$

Python

can be made to look horrible too

from itertools import cycle
for x in cycle((2**2,2**2*2,2**2**2-7+2*2+2,2**2**2,(2**2*2*6-2)/2,2**2*2*6-6)):print x
\$\endgroup\$
1
vote
\$\begingroup\$

C

A few (implementation dependent) ideas:

1

main()
{
    char a[] = "uKyKrvKrwKstKusK";
    unsigned int i;

    for(i = 0; i >= 0; i++)
    {
        printf("%c", (char)(a[i&(sizeof(a)-2)] - 'A'));
    }
}

2

#include <stdio.h>
#include <string.h>
#include <float.h>

#define Answer_to_the_Ultimate_Question_of_Life_The_Universe_and_Everything  I_may_be_a_sorry_case_but_I_dont_write_jokes_in_base_13(Six by nine)
#define Six 0b110
#define by *
#define nine 0b1001
#define I_may_be_a_sorry_case_but_I_dont_write_jokes_in_base_13(x) 10*(x/13)+x%13

void PrintNumSequence(void);

int main(void)
{
    PrintNumSequence();
}

/*
Prints out the following sequence forever: http://lostpedia.wikia.com/wiki/The_Numbers
*/
void PrintNumSequence(void)
{
    int a[] = {sizeof(int), sizeof(double), DBL_DIG, strlen(__func__), __LINE__, Answer_to_the_Ultimate_Question_of_Life_The_Universe_and_Everything};
    unsigned int i;

    while(1)
    {
        for(i = 0; i < sizeof(a)/sizeof(a[0]); i++)
        {
            printf("%d \n", a[i]);
        }
    }
}
\$\endgroup\$
2
votes
\$\begingroup\$

Fortran 95

program NO_NUMBERS_ALLOWED
implicit none

integer :: i, aux_A, aux_B
integer, allocatable :: array(:)

aux_A = iachar("!") - iachar(" ")
aux_B = iachar("&") - iachar(" ")

allocate(array(aux_A:aux_B))

array(aux_A:aux_B) = (/(iachar("$") - iachar(" ")), (iachar("(") - iachar(" ")), (iachar("/") - iachar(" ")), &
(iachar("~") - iachar("n")), (iachar("{") - iachar("d")), iachar("*")/)

i = aux_A
do
  print*, array(i)
  i = i + aux_A
  if (i==(aux_B + aux_A)) i = aux_A
enddo

end program NO_NUMBERS_ALLOWED

The variables aux_A and aux_B have their values defined via the function iachar(c), which converts a character into its integer ASCii value. The variable array contains all six values defined via mathematical operations and the already mentioned function. This array is then infinitely printed in order in the screen via an endless loop.

\$\endgroup\$
  • \$\begingroup\$ Why the negative vote? Did I miss something here? \$\endgroup\$ – gilbertohasnofb Mar 12 '14 at 17:00
  • \$\begingroup\$ Probably because there has been another answer with the same idea, or it is because the idea is boring. \$\endgroup\$ – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Mar 22 '14 at 16:38
1
vote
\$\begingroup\$

C++

#include<iostream>
int main()
{
    for(;;)
        std::cout<<'\n'-6<<", "<<'\n'-2<<", "<<'\n'+5<<", "<<'\n'+6<<", "<<' '-9<<", "<<'*'+0<<", ";
}
\$\endgroup\$
  • \$\begingroup\$ Could down-voter explain why he/she don't like the answer ? \$\endgroup\$ – Mukul Kumar Mar 13 '14 at 3:24
  • 1
    \$\begingroup\$ Could be because this is basically the same as the "valid, but uninspired" version in the OP. \$\endgroup\$ – Geobits Mar 13 '14 at 12:56
2
votes
\$\begingroup\$

JavaScript (ES6)

while(true) "$(/07J".split('').map(i=>String.charCodeAt(i)-32).forEach(i=>console.log(i));

or, with non-printable characters,

while(true) "*".split('').map(i=>String.charCodeAt(i)).forEach(i=>console.log(i));
\$\endgroup\$
185
votes
+250
\$\begingroup\$

Python

#!/usr/bin/python
lizt = ["SPOI",
        "LERS: Lo",
        "st begins with ",
        "a plane crash on",
        "a desert island and end",
        "s with its viewers stuck in limbo forever."
        ]

while True:
    for item in lizt:
        print len(item)

Edit: As per nneonneo's suggestion, script now includes no digits.

\$\endgroup\$
  • 2
    \$\begingroup\$ So simple, and yet so good. \$\endgroup\$ – Konrad Borowski Mar 13 '14 at 13:22
  • 4
    \$\begingroup\$ Whether or not this gets my vote depends entirely on the answer to this question: is the spelling of "lizt" an "Arzt" reference? EDIT: Who am I kidding, it gets my vote anyhow. \$\endgroup\$ – Plutor Mar 13 '14 at 14:11
  • 6
    \$\begingroup\$ I would write while True: so that your answer contains no digits at all. \$\endgroup\$ – nneonneo Mar 14 '14 at 1:07
  • 2
    \$\begingroup\$ while True: is more common. \$\endgroup\$ – Martin Ueding Mar 17 '14 at 14:09
  • 1
    \$\begingroup\$ Doesn't that spoil the "no alternative bases" rule? Basically, it's just an array of base-1 numbers :-) \$\endgroup\$ – Daniel Mar 24 '14 at 22:15
3
votes
\$\begingroup\$

C

The formula

a[i] = a[i-1] + a[i-3] + a[i-5]

works with proper initialization: -5, -3, 7, 8, -3, -1, 4, 8, 15, 16, 23, 42, 66, and so on. (Note that unfortunately, the number 8 appears twice in this sequence.)

The following slightly golfed ANSI C program generates the six numbers by initializing and iterating. It then loops forever printing them, as was requested.

#include <stdio.h>
int main() {
    int a[] = { -5, -3, 7, 1<<3, -3, -1 };
    int j = 0;
    for (; ++j<7; ) a[(j-1)%6] = a[j%6] + a[(2+j)%6] + a[(4+j)%6];
    for (;;) for (j=0; j<6; j++) printf("%d\n", a[j]);
}
\$\endgroup\$
2
votes
\$\begingroup\$

C++

Haven't decided yet how ugly I think this is. Probably very :-)

#include <iostream>

double b, f[2];

float func(float x)
{
  // Maybe I should just choose a value for b here, instead of randomizing
  return 2+(x-1)*((x-b)*((-b+x-1)*(((((7/(b+1)-1/b)/(2*b+1)-
         (1/b-7)/(b+1))/(2*b+2)-((1/b-7)/(b+1)-(7-2/(b-1)*2)/b)/(2*b))*
         (-2*b+x-1))/(3*b+1)+((1/b-7)/(b+1)-(7-2/(b-1)*2)/b)/(2*b))+
         (7-2/(b-1)*2)/b)+2/(0.5*b-0.5))+2;
}

float fib()
{
  return f[0] = (f[1] += f[0]) - f[0], f[1];
}

int levels = 0;

int main() {
  f[0] = 1;
  b = f[1] = ((int)(&f)) & 0xee;

  std::cout << func(f[0]) << std::endl;
  std::cout << func(f[1]) << std::endl;
  std::cout << func(fib()) << std::endl;
  std::cout << func(fib()) << std::endl;
  std::cout << func(fib()) << std::endl;

  return main();
}

If you intend to have it run forever, make sure you have enough (i.e. infinite) stack.

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

C

void main(int a, char **b){
    char s[]={'/'-'\'','/'- ' ','_' - 'O','^' - 'G','~' - 'T',',' - '('};
    c:printf("%d ", s[(++a)%6]); goto c;
}
\$\endgroup\$
55
votes
\$\begingroup\$

Brainfuck

I'm so bad at ASCII art !

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

Test it here : http://ideone.com/kh3DYI

\$\endgroup\$
  • \$\begingroup\$ This is a really nice solution :) \$\endgroup\$ – gilbertohasnofb Mar 13 '14 at 15:14
22
votes
\$\begingroup\$

C

Get your squinting goggles on :-)

main(         i){char*s     ="*)2;,5p   7ii*dpi*t1p+"
"={pi       7,i)?1!'p)(a! (ii(**+)(o(,( '(p-7rr)=pp="
"/(('       (^r9e   n%){1 !ii):   a;pin     7,p+"
"{*sp       ;'*p*   op=p) in,**             i+)s"
"pf/=       (t=2/   *,'i% f+)0f7i=*%a       (rpn"
"p(p;       )ri=}   niipp   +}(ipi%*ti(     !{pi"
"+)sa       tp;}*   s;}+%         *n;==     cw-}"
"9{ii       i*(ai   a5n(a +fs;i   *1'7",    *p=s-
1;while(p=('T'^i)?++p:s){ for(i=1;55!=*     p;p++
)i+=(' '!=*   p);printf     ("%d ",i/       2);}}
\$\endgroup\$
  • 11
    \$\begingroup\$ As pretty as this may be, I count three 4s and two 8s in there. \$\endgroup\$ – Geobits Mar 13 '14 at 2:33
  • 6
    \$\begingroup\$ @Geobits I obviously need a new pair of squinting goggles! Fixed now. \$\endgroup\$ – squeamish ossifrage Mar 13 '14 at 8:28
2
votes
\$\begingroup\$

Brainf**k

-[----->+<]>+.-[
--->++<]>--.----
[->++<]>.[-->+<]
>++++.[-->+++<]>
+.++++.--[--->++
<]>--.[-->+++<]>
+.+++++.[-->+<]>
+++++.[-->+++<]>
++.+.[--->++<]>-
-.++[-->+++<]>+.                       :=-=-=.
\$\endgroup\$
44
votes
\$\begingroup\$

C#

Formula "stolen" from https://oeis.org/A130826 : a(n) is the smallest number such that twice the number of divisors of (a(n)-n)/3 gives the n-th term in the first differences of the sequence produced by the Flavius-Josephus sieve.

using System;
using System.Collections.Generic;
using System.Linq;

public static class LostNumberCalculator
{
    public static int GetNumber(int i)
    {
        int a = GetPairwiseDifferences(GetFlaviusJosephusSieveUpTo(100)).ElementAt(i);
        int b = FindSmallestNumberWithNDivisors(a / 2);
        return b * 3 + i + 1;
    }

    public static IEnumerable<int> GetFlaviusJosephusSieveUpTo(int max)
    {
        List<int> numbers = Enumerable.Range(1, max).ToList();

        for (int d = 2; d < max; d++)
        {
            List<int> newNumbers = new List<int>();
            for (int i = 0; i < numbers.Count; i++)
            {
                bool deleteNumber = (i + 1) % d == 0;
                if (!deleteNumber)
                {
                    newNumbers.Add(numbers[i]);
                }
            }
            numbers = newNumbers;
        }

        return numbers;
    }

    public static IEnumerable<int> GetPairwiseDifferences(IEnumerable<int> numbers)
    {
        var list = numbers.ToList();
        for (int i = 0; i < list.Count - 1; i++)
        {
            yield return list[i + 1] - list[i];
        }
    }

    public static int FindSmallestNumberWithNDivisors(int n)
    {
        for (int i = 1; i <= int.MaxValue; i++)
        {
            if (CountDivisors(i) == n)
            {
                return i;
            }
        }
        throw new ArgumentException("n is too large");
    }

    public static int CountDivisors(int number)
    {
        int divisors = 0;
        for (int i = 1; i <= number; i++)
        {
            if (number % i == 0)
            {
                divisors++;
            }
        }
        return divisors;
    }
}

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            for (int i = 0; i < 6; i++)
            {
                int n = LostNumberCalculator.GetNumber(i);
                Console.WriteLine(n);
            }
        }
    }
}
\$\endgroup\$
  • 10
    \$\begingroup\$ +1 For someone that actually went to oeis.org in order to research a formula that fits the sequence :) \$\endgroup\$ – MrPaulch Mar 17 '14 at 6:57
  • \$\begingroup\$ a(i)=a(i-1)+a(i-3)+a(i-5) really seems like an easier solution \$\endgroup\$ – Cruncher Mar 20 '14 at 20:40
  • 1
    \$\begingroup\$ @Cruncher That formula requires you to predefine the first 5 terms (including 4, 8 and 15), which is both boring and against the rules. \$\endgroup\$ – Sebastian Negraszus Mar 20 '14 at 21:01
3
votes
\$\begingroup\$

VBA

 ns = Split("I Di|dn't| like L|O|ST past| Season 2. Downhill", "|")
 Do While True: n = LBound(ns): For i = LBound(ns) To UBound(ns): n = n + Len(ns(i)): Debug.Print n: Next i: Loop

leave option explicit off

\$\endgroup\$
234
votes
\$\begingroup\$

Java

I decided to add another entry since this is completely different from my first one (which was more like an example).

This program calculates the average of an array entered by the user...

import java.util.Scanner;

public class Numbers {
    public static double getSum(int[] nums) {
        double sum = 0;
        if(nums.length > 0) {
            for(int i = 0; i <= nums.length; i++) {
                sum += nums[i];
            }
        }

        return sum;
    }

    public static double getAverage(int[] nums) { return getSum(nums) / nums.length; }
    public static long roundAverage(int[] nums) { return Math.round(getAverage(nums)); }

    private static void beginLoop(int[] nums) {
        if(nums == null) {
            return;
        }

        long avg = roundAverage(nums);
        System.out.println("enter nums for average");
        System.out.println("example:");
        System.out.print("array is " + nums[0]);
        for(int i = 1; i <= nums.length; i++) {
            System.out.print(", " + nums[i]);
        }

        System.out.println();
        System.out.println("avg is " + avg);
    }

    private static int[] example = { 1, 2, 7, 9, };

    public static void main(String[] args) {
        boolean done = false;
        while(!done) {
            try {
                int[] nums = example;
                beginLoop(nums);

                nums = getInput();
                if(nums == null) {
                    done = true;
                } else {
                    System.out.println("avg is " + getAverage(nums));
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    static int[] getInput() {
        Scanner in = new Scanner(System.in);
        System.out.print("enter length of array to average or 0 to exit: ");
        int length = in.nextInt();
        if(length == 0) {
            return null;

        } else {
            int[] nums = new int[length];
            for(int i = 0; i <= nums.length; i++) {
                System.out.print("enter number for index " + i + ": ");
                nums[i] = in.nextInt();
            }
            return nums;
        }
    }
}

...or does it?

java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    at Numbers.getAverage(Numbers.java:15)
    at Numbers.roundAverage(Numbers.java:16)
    at Numbers.beginLoop(Numbers.java:23)
    at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    at Numbers.getAverage(Numbers.java:15)
    at Numbers.roundAverage(Numbers.java:16)
    at Numbers.beginLoop(Numbers.java:23)
    at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    ...
\$\endgroup\$
  • 17
    \$\begingroup\$ This is great! I would not have thought of something like that. \$\endgroup\$ – Jordon Biondo Mar 12 '14 at 21:48
  • 2
    \$\begingroup\$ Wow, beautiful ! Great idea ;) \$\endgroup\$ – Pierre Arlaud Mar 13 '14 at 8:25
  • 5
    \$\begingroup\$ Genius! Though the output is a bit verbose, but I guess that has to do with the language you chose here. ;) \$\endgroup\$ – Pieter Witvoet Mar 13 '14 at 12:30
  • 3
    \$\begingroup\$ Just when I thought the Python "lizt=Lost plot" one couldn't be topped... \$\endgroup\$ – Dave Mar 14 '14 at 14:27
  • 3
    \$\begingroup\$ @justhalf Actually it bugs me this was the top answer for a little while there. It's no fun to win my own question. \$\endgroup\$ – Radiodef Mar 20 '14 at 6:59
14
votes
\$\begingroup\$

Bash one-liner

yes `curl -s "https://oeis.org/search?q=id:A$((130726+100))&fmt=text" |
grep %S | cut -d " " -f 3 | cut -d "," -f 1-6`

Line break added for readability. It (ab)uses the fact that these are the first six numbers of OEIS Sequence A130826.

\$\endgroup\$
  • \$\begingroup\$ You can also pipe awk -F"[ ,]" '/%S/ {for (i=3;i<=9;i++) printf $i" "}' to curl. \$\endgroup\$ – fedorqui Mar 13 '14 at 13:18
  • 1
    \$\begingroup\$ You can remove the loop altogether with yes and drop the redirect to /dev/null with curl -s. Something like yes $(curl -s "https://oeis.org/search?q=id:A$((130726+100))&t=text" | awk -F"[ ,]" '/%S/ {for (i=3;i<9;i++) printf $i" "}') \$\endgroup\$ – Digital Trauma Mar 14 '14 at 6:20
  • \$\begingroup\$ @DigitalTrauma: Thanks, I did not know about yes and curl -s -- I just shamelessly added this to my answer. :-) \$\endgroup\$ – Heinzi Mar 14 '14 at 6:33
12
votes
\$\begingroup\$

I like the idea of using the sequence

a[n+5] = a[n] + a[n+2] + a[n+4]

as in this answer. Found it through the OEIS Search as sequence A122115.

If we go through the sequence in reverse we will find a suitable initialization quintuple that doesn’t contain 4, 8, 15, 16 or 23.

Python3:

l = [3053, 937, -1396, -1757, -73]
while l[-1] != 66:
    l.append(l[-5] + l[-3] + l[-1])
while True:
    print(l[-6:-1])
\$\endgroup\$
  • \$\begingroup\$ very clever! Nice. \$\endgroup\$ – DavidC Mar 25 '14 at 12:26
6
votes
\$\begingroup\$

Julia

By researching a while i found a mathematical way to express the sequence by other sequences without using any of the numbers (or tricky ways to use them):

L(n)=n==0?2:n==1?1:L(n-1)+L(n-2) #Lucas numbers.
O(n)=int(n*(n+1)*(n+2)/6)
S(n)=n in [O(i) for i=1:50]?0:1 #A014306
T(n)=begin k=ifloor(n/2);sum([L(i)*S(n+1-i) for i=1:k]) end #A025097

lost(n)=n>5?lost(n-1)+lost(n-3)+lost(n-5):(n+3)>5?T(n+3):-T(n+3) #A122115

[lost(i-2) for i=5:10]

Output:

6-element Array{Int64,1}:
  4
  8
 15
 16
 23
 42
\$\endgroup\$
0
votes
\$\begingroup\$

VBA

Sub chr_la_head_chr_la()
n = 50
Do While (True)
MsgBox Chr(n + 2) & " " & Chr(n + 6) & " " & Chr(n - 1) & Chr(n + 3) & " " & Chr(n - 1) & Chr(n + 3 + 1) & " " & Chr(n) & Chr(n + 1) & " " & Chr(n + 2) & Chr(n)  
Loop
End Sub
\$\endgroup\$

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