ubuntuusers.de

Code Gala

Code Gala ist ein Projekt der ubuntuusers.de-Mitglieder. Programmierer erstellen zu verschiedenen Aufgaben ihre Lösungen in ihren Lieblingssprachen.

Lychrel Zahlen (04.03.2008)

BASH

von Mr. Kanister (sehr langsam & nur Zahlen < 1000)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#!/bin/bash
for (( i = 1; i <= 1000; i++ ))
do
   zahl=$i
   for (( j = 1; j <= 100; j++ ))
   do
      zahl=$(echo "$zahl + $(echo $zahl | rev)" | bc)
      [[ "$zahl" == "$(echo $zahl | rev)" ]] && break
      (( j == 100 )) && echo $i
   done
done

von rocco_storm (sehr langsam & nur Zahlen < 1000)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/bin/bash

i=1
last=1000
iterations=100
x=0

isPalindrom ()
{
   if [[ "$x" == "$(echo $x | rev)" ]]
   then
      return 0
   else
      return 1
   fi
}

isLychrel ()
{
   j=0
   x=$i
   while [ "$j" -lt "$iterations" ]
   do
      x=$(echo "$x + $(echo $x | rev)" | bc)
      if isPalindrom
      then
         return 1
      fi
      (( j += 1 ))
   done
   return 0
}

while [ "$i" -lt "$last" ]
do
   if isLychrel
   then
      echo "-------------> Found Lychrel: $i"
   fi
   (( i += 1 ))
done
echo
exit 0

C

von Marc 'BlackJack' Rintsch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <string.h>

#define FROM        1
#define TO          100000
#define TO_DIGITS   10
#define ITERATIONS  100
#define MAX_DIGITS  (TO_DIGITS + ITERATIONS)

static unsigned int n_length, length;
static char n[TO_DIGITS], a[MAX_DIGITS], b[MAX_DIGITS];

static void reverse_add(void)
{
    unsigned int i, carry, tmp;
    
    for (i = 0, carry = 0; i < length; i++) {
        tmp = a[i] + a[length - 1 - i] + carry;
        if (tmp >= 10) {
            tmp = tmp - 10;
            carry = 1;
        } else {
            carry = 0;
        }
        b[i] = tmp;
    }
    if (carry) {
        b[i] = carry;
        length++;
    }
}

static int is_palindrome(void)
{
    char *x, *y;
    
    x = b;
    y = b + length - 1;
    while (x < y) {
        if (*x++ != *y--) return 0;
    }
    return 1;
}

static int is_lychrel()
{
    unsigned int i;
    
    memcpy(a, n, n_length);
    length = n_length;
    for (i = 0; i < ITERATIONS; i++) {
        reverse_add();
        if (is_palindrome()) return 0;
        memcpy(a, b, length);
    }
    return 1;
}

static void print_n(void)
{
    int i;
    for (i = n_length - 1; i >= 0; i--) {
        printf("%c", n[i] + '0');
    }
    printf("\n");
}

static void increase_n(void)
{
    char *x = n;
    
    while ((*x)++ == 9) {
        *x++ = 0;
    }
    if (x - n == n_length) n_length++;
}

int main(void)
{
    unsigned int i;
    
    n_length = sprintf(a, "%d", FROM);
    for (i = 0; i < n_length; i++) {
        n[i] = a[n_length - 1 - i] - '0';
    }

    for (i = FROM; i <= TO; i ++) {
        if (is_lychrel()) {
            print_n();
        }
        increase_n();
    }
    return 0;
} 

C++

von Hello World (Benötigt libgmpxx4ldbl und den Compilerswitch -lgmpxx)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <gmpxx.h>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
bool is_palindrome(const mpz_class& x) {
    stringstream ss;
    ss << x;
    string s = ss.str();
    int i1 = s.length()-1, i2=0;
    while (i1 >= i2) {
        if (s[i1] != s[i2])
            return false;
        i1--;
        i2++;
    }
    return true;
}
mpz_class reverse(const mpz_class& x) {
    stringstream ss;
    mpz_class rv;
    ss << x;
    string s = ss.str();
    reverse(s.begin(),s.end());
    ss.str(s);
    ss >> rv;
    return rv;
}
bool is_lychrel(const mpz_class& x, int iterations) {
    mpz_class y = x;
    for (int i=0;i<iterations;++i) {
        y+=reverse(y);
        if (is_palindrome(y))
            return false;
    }
    return true;
}
int main() {
    cout.sync_with_stdio(false);
    for (int i=0;i<100000;++i) {
        if (is_lychrel(i,100))
            cout << i << '\n';
    }
}

von Mr. Kanister (nur 20 Iterationen)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <sstream>
using namespace std;

unsigned long long int revers(unsigned long long int zahl);
bool is_palin(unsigned long long int zahl);

int main(int argc, char** argv) {

	unsigned long long int zahl;

	for (int i = 1; i <= 100000; i++) {
		zahl = i;

		for (int j = 1; j <= 20; j++) {
			zahl += revers(zahl);
			if (is_palin(zahl)) {
				break;
			}

			if (j == 20) {
				cout << i << " könnte eine Lychrel-Zahl sein\n";
			}
		}
	}

	return EXIT_SUCCESS;
}

unsigned long long int revers(unsigned long long int zahl) {
	stringstream buf;
	
	while (zahl != 0) {
		buf << zahl % 10;
		zahl /= 10;
	}

	buf >> zahl;

	return zahl;
}

bool is_palin(unsigned long long int zahl) {
	if (zahl == revers(zahl)) {
		return true;
	} else {
		return false;
	}
} 

von Tux90 (nur 20 Iterationen)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <sstream>
using namespace std;

/* Gibt alle Lychrel-Zahlen zwischen 11 und 100000 aus */

unsigned long long reverse( unsigned long long zahl) //Dreht die Zahl um
{
      stringstream stream, s;
      string asstring, reverse;
      unsigned long long rev = 0;
      stream << zahl;
      stream >> asstring;
      stream.flush();

      for( int i = (asstring.length()-1); i >= 0 ; i-- ) {
	  s << asstring.at(i);
      }
      s >> rev;
    
      return rev;
}

bool is_palin( unsigned long long zahl )  //Überprüft, ob zahl ein Palindrom ist
{
      if( reverse(zahl) == zahl ) return true;
      return false;
}

int main()
{
      bool is_lychrel = true;
      unsigned long long zahl = 0;

      for( int z = 11; z <= 100000; z++ ) {
	  is_lychrel = true;
	  zahl = z;
	  for( int i = 0; i <= 20; i++ ) {
	      zahl = zahl + reverse(zahl);
	      if( is_palin(zahl) ) {
		  is_lychrel = false;
		  break;
	      }
	  }
      
	  if( is_lychrel ) cout << z << " könnte eine Lychrel-Zahl sein!" << endl;

      }
      return 0;
}

D

von Marc 'BlackJack' Rintsch

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111

import std.stdio;
import std.string;

static const uint ITERATIONS = 100;

class Integer
{
    ubyte[] digits;
   
    invariant {
        foreach (ubyte d; digits) {
            assert(0 <= d && d < 10);
        }
    }
   
    this(uint n)
    out { assert(this.toInt == n); }
    body
    {
        char[] d = std.string.toString(n);
        this.digits = new ubyte[d.length];
        foreach (uint i, char c; d) {
            this.digits[$-1-i] = c - '0';
        }
    }
   
    this(Integer i)
    out { assert(this.digits !is i.digits);  }
    body
    {
        this.digits = new ubyte[i.length];
        this.digits[] = i.digits;
    }
   
    Integer opAdd(Integer other)
    {
        auto result = new Integer(this);
        uint carry = 0;
        foreach (uint i, inout ubyte b; result.digits) {
            b = b + other.digits[i] + carry;
            if (b >= 10) {
                b -= 10;
                carry = 1;
            } else {
                carry = 0;
            }
        }
        if (carry) {
            result.digits.length = result.digits.length + 1;
            result.digits[$-1] = carry;
        }
        return result;
    }
   
    uint length() { return this.digits.length; }
   
    bool isPalindrome()
    {
        for (uint i = 0; i < this.length / 2; i++) {
            if (this.digits[i] != this.digits[$-1-i]) return false;
        }
        return true;
    }
   
    Integer reversed()
    {
        auto result = new Integer(this);
        for (uint i = 0; i < result.length / 2; i++) {
            auto tmp = result.digits[i];
            result.digits[i] = result.digits[$-1-i];
            result.digits[$-1-i] = tmp;
        }
        return result;
    }
   
    char[] toString()
    {
        auto result = new char[this.length];
        foreach (uint i, ubyte b; this.digits) {
            result[i] = this.digits[$-1-i] + '0';
        }
        return result;
    }
   
    uint toInt()
    {
        uint result = 0;
        foreach_reverse (ubyte b; this.digits) {
            result = result * 10 + b;
        }
        return result;
    }
}

bool isLychrel(Integer n, uint iterations = ITERATIONS)
{
    for (uint i = 0; i < iterations; i++) {
        n = n + n.reversed;
        if (n.isPalindrome) return false;
    }
    return true;
}

void main()
{
    for (uint n = 1; n <= 100_000; n++) {
        auto i = new Integer(n);
        if (isLychrel(i)) writef("%s\n", i);
    } 
}

Erlang

von radoe2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
-module(lychrel).
-export( [is_palindrom/1, inversion/1, lychrel/3, start/0]).

%-- is_palindrom
is_palindrom(AnInteger)   ->
    L = integer_to_list(AnInteger),
    R = lists:reverse(L),
    ZipWithFun = fun( E1, E2 ) -> E1 == E2 end,
    Zipped = lists:zipwith(ZipWithFun, L, R),
    %% lists:any here returns true if L is *not* a palindrom, so negate it.
    false == lists:any( fun(X) -> X == false end, Zipped);

%-- inversion
inversion(AnInteger) ->
    list_to_integer (lists:reverse( integer_to_list(AnInteger))).

%-- find_lychrel   
find_lychrel(OriginalStart, Current, 0) ->
    case is_palindrom(Current) of
        true -> ok;
        false -> io:format("~w~n", [OriginalStart])
    end;

find_lychrel(OriginalStart, Current, CurrentIter) ->
    case is_palindrom(Current) of
        true -> ok;
        false -> find_lychrel(OriginalStart, Current + inversion(Current), CurrentIter -1 )
    end.

%-- lychrel
lychrel(End,End,_) ->
    ok;

lychrel(Start,End,MaxIter) ->
    find_lychrel(Start, Start, MaxIter),
    lychrel(Start+1, End, MaxIter).
   
%for convenience, assume Start=1,End=N,MaxIter=100
lychrel(N) ->        
    lychrel(1,N,100).
                
%-- for calling this as "erl -noshell -s lychrel start"
start() ->
    lychrel(100000),
    init:stop().

Fortran

von GerritK (nur 25 Iterationen)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

program Lychrel_Zahl
  implicit none 
  
  integer, parameter :: lang = selected_int_kind(16)
  integer(kind=lang) :: z1, z2
  integer            :: i, z, n=0
    
  do z=100000,0,-1
     z1  = z    
     do i=0,25
        call reverse(z1, z2)
        z1 = z1 + z2
        call reverse(z1, z2)
        if (z1 == z2) exit
        if (i  == 25) print*, z 
     enddo    
  enddo 

end program


subroutine reverse(z1, z2)
  implicit none

  integer, parameter :: lang = selected_int_kind(16) 
  integer(kind=lang), intent(in)  :: z1
  integer(kind=lang), intent(out) :: z2
  integer(kind=lang) :: zahl
  integer            :: hilf

  z2   = 0
  zahl = z1

  do
     hilf =  modulo(zahl,10)
     zahl = (zahl-hilf)/10 
     z2   = 10 * z2 + hilf 
     if (zahl == 0) exit
  enddo

  return

end subroutine

Haskell

von Marc 'BlackJack' Rintsch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

import Char (digitToInt)

type Digits = [Int]

intToDigits :: Int -> Digits
intToDigits = reverse . map digitToInt . show

add :: Digits -> Digits -> Digits
add xs ys = add' xs ys 0
    where
        add' [] [] 0 = []
        add' [] [] 1 = [1]
        add' (a:as) (b:bs) c =
            let s = a + b + c in
                (s `mod` 10) : add' as bs (s `div` 10)

reverseAndAdd :: Digits -> Digits
reverseAndAdd ds = add ds (reverse ds)

isPalindrome :: Digits -> Bool
isPalindrome ds = ds == (reverse ds)

isLychrel :: Int -> Int -> Bool
isLychrel i n = not . any isPalindrome . take i . tail
    $ iterate reverseAndAdd (intToDigits n)

lychrelNumbers :: Int -> Int -> Int -> [Int]
lychrelNumbers a b m = filter (isLychrel m) [a..b]

main :: IO ()
main = mapM_ print $ lychrelNumbers 1 100000 100

von rocco_storm

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
module Main where
{-
Integer - die zu testende Zahl
Bool - True wenn es ein Palindrom ist
-}
isPalindrom :: Integer -> Bool
isPalindrom x = show x == reverse (show x)

{-
Integer(1) - die zu testende Zahl
Integer(2) - Anzahl der Iterationen
Bool - True wenn es eine Lychrel-Zahl ist
-}
isLychrel :: Integer -> Integer -> Bool
isLychrel x y   | isPalindrom x = False
            | not (isPalindrom x) && y > 0 = isLychrel (x+(read(reverse(show x))::Integer)) (y-1)
            | not (isPalindrom x) && y <= 0 = True

{-
Integer(1) - Letzte zu testende Zahl
Integer(2) - Aktuell zu testende Zahl
Integer(3) - Anzahl der Iterationen Pro Zahl
[Integer] - Liste der Lychrel-Zahlen
-}
lychrelTest :: Integer -> Integer -> Integer -> [Integer] -> [Integer]
lychrelTest x y z xs   | y>x = xs
                  | y<=x && isLychrel y z = lychrelTest x (y+1) z xs++[y]
                  | y<=x && not (isLychrel y z) = lychrelTest x (y+1) z xs
lychrelTest x y z []   | y>x = []
                  | y<=x && isLychrel y z = lychrelTest x (y+1) z [y]
                  | y<=x && not (isLychrel y z) = lychrelTest x (y+1) z []


{-
Integer(1) - Zu testende Zahlen
Integer(2) - Iterationen pro Zahl
[Integer] - Liste der Lychrel-Zahlen
-}
main :: Integer -> Integer -> [Integer]
main x y = lychrelTest x 1 y [] 

Java

von kart0ffelsack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.math.BigInteger;

public class Lychrel {
   
   public static boolean isPalindrom(BigInteger x) {
      return spiegel(x).equals(x);
   }
   
   static BigInteger spiegel(BigInteger x) {
      String cl = x.toString();
      String neu = new StringBuffer(cl).reverse().toString();
      return new BigInteger(neu);
   }
   
   static boolean lychrel(int x) {
      BigInteger a = BigInteger.valueOf(x);
      
      for(int i = 0;i < 100;i++) {
         if(isPalindrom(a=a.add(spiegel(a)))) return false;
         //System.out.println(a.toString());
      }
      return true;
   }
   
   public static void main(String[] args) {
      int erg = 0;
      long start = System.currentTimeMillis();
      for(int i = 1;i <= 100000;i++) {
         if(lychrel(i)) {
            System.out.println(i);
            erg++;
         }
      }
      long stop = System.currentTimeMillis();
      System.out.println("Anzahl: " + erg);
      System.out.println("Zeit: " + (stop - start) + "ms");
   }
}

von rocco_storm

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.math.BigInteger;

public class lychrel3 {

   public static void main(String[] args) {
         int anz = 0;
         int last = 100000;
         int iter = 100;
         long start = System.currentTimeMillis();
         for(int i = 1;i <= last;i++) {
             BigInteger z = BigInteger.valueOf(i);
            for (int j=1;j<=iter;j++) {
               z=z.add(new BigInteger(new StringBuffer(z.toString()).reverse().toString()));
               if(new BigInteger(new StringBuffer(z.toString()).reverse().toString()).equals(z)) break;
               if (j==iter) {
                  System.out.println(i);
                  anz++;
             }
            }
         }
         long stop = System.currentTimeMillis();
         System.out.println("anz:  " + anz);
         System.out.println("time: " + (stop - start) + "ms");
      }
}

von fnumatic

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public class LychrelTest {

    public static void main(String[] args) {
        new LychrelTest().run();
    }

    public void run() {
        int count = 0;
        long start = System.currentTimeMillis();
        for (int i = 1; i < 100000; i++) {
            if (checkLychrel( i )) {
                count++;
                System.out.println( "prob lychrel = " + i );
            }
        }
        long stop = System.currentTimeMillis();
        System.out.println( "count:  " + count );
        System.out.println( "time: " + ( stop - start ) + "ms" );
    }

    public boolean checkLychrel(int i) {
        LargeInt largeInt = new LargeInt( i );
        for (int j = 1; j <= 100; j++) {
            largeInt = largeInt.add( largeInt.reverse() );
            if (largeInt.isPalindrom()) return false;
        }
        return true;
    }

    final class LargeInt {
        List<Integer> digits;

        public LargeInt(List<Integer> list) {
            digits = list;
        }

        public LargeInt(int value) {
            digits = new ArrayList<Integer>();
            while (value != 0) {
                digits.add( value % 10 );
                value /= 10;
            }
        }

        public LargeInt add(LargeInt addend) {
            Iterator<Integer> addendIterator = addend.digits.iterator();
            List<Integer> result = new ArrayList<Integer>( digits.size() );
            int carry = 0;
            for (int digit : digits) {
                int sum = digit + addendIterator.next() + carry;
                result.add( sum % 10 );
                carry = sum / 10;
            }

            if (carry != 0) result.add( carry );
            return new LargeInt( result );
        }

        public LargeInt reverse() {
            List<Integer> result = new ArrayList<Integer>( digits );
            Collections.reverse( result );
            return new LargeInt( result );
        }

        public boolean isPalindrom() {
            LinkedList<Integer> list = new LinkedList<Integer>( digits );
            while (list.size() > 1) {
                if (!list.removeFirst().equals(list.removeLast())) {
                    return false;
                }
            }
            return true;
        }
    }

}

Pascal

von sh4711 (Benötigt libgmpX-dev )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
program lychrelzahl;
uses SysUtils, StrUtils, gmp;
var
  z, zr, zpd, zpdr : mpz_t;
  i, count : longint;

begin
  mpz_init_set_ui(z,0);
  mpz_init_set_ui(zr,0);
  mpz_init_set_ui(zpd,0);
  mpz_init_set_ui(zpdr,0);
  try
    for i := 1 to 100000 do
    begin
      mpz_set_ui(z,i);
      for count := 1 to 100 do
      begin
        mpz_set_str(zr, Pchar(ReverseString(StrPas(mpz_get_str(Nil,10,z)))),10);
        mpz_add(zpd,z,zr);
        mpz_set_str(zpdr, Pchar(ReverseString(StrPas(mpz_get_str(Nil,10,zpd)))),10);
        if not (mpz_cmp(zpd,zpdr) = 0) then
        begin
          mpz_set(z,zpd);
          if count = 100 then
            writeln(i);
        end
        else //else Palindrom break
          break;
      end;
    end;
  finally
    mpz_clear(z);
    mpz_clear(zr);
    mpz_clear(zpd);
    mpz_clear(zpdr);
  end;
end.

Python

von Marc 'BlackJack' Rintsch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/env python

def is_palindrome(number):
    number_as_string = str(number)
    return number_as_string == number_as_string[::-1]

def is_lychrel(number, iterations):
    for dummy in xrange(iterations):
        number += int(str(number)[::-1])
        if is_palindrome(number):
            return False
    return True

def main():
    first = 1
    last = 100000
    iterations = 100
    for number in xrange(first, last + 1):
        if is_lychrel(number, 100):
            print number

if __name__ == '__main__':
    main()

von audax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from itertools import ifilter, imap

def mirror(n):
    return int(
                str(n)[::-1])

def is_lychrel(n, tries=100):
    rev = mirror(n)
    for dummy in xrange(tries):
        n += rev
        rev = mirror(n)
        if n == rev:
            return False
    return True

def main():
    print '\n'.join(imap(str, ifilter(is_lychrel, xrange(100000))))

if __name__ == '__main__':
    main()

Ruby

von BadBoy

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18

def reverse zahl
  zahl.to_s.reverse.to_i
end

def is_lychrel n, tries=100
  rev = reverse n
  1.upto(tries) {
    n += rev
    rev = reverse n
    return false if n == rev
  }
  true
end

1.upto(ARGV[0] ? ARGV[0].to_i : 100000) { |i|
  print i, " könnte eine Lychrel-Zahl sein\n" if is_lychrel i
}

von Adna rim

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/env ruby
$VERBOSE=true

0.upto(100000) do |i|
        lychrel=i
        palin=false
        100.times do
                i += i.to_s.reverse.to_i
                (i.to_s == i.to_s.reverse) && (palin=true;break)
        end
        !palin && puts(lychrel)
end 

Scala

von user unknown

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
object Lychrel {

  def isPalindrom (x: BigInt): Boolean =
    spiegel (x).equals (x)

  def spiegel (x: BigInt): BigInt = {
    var sb = new StringBuffer (x.toString ())
    BigInt (sb.reverse ().toString ())
  }
  
  def lychrel (x: BigInt, sofar: Int = 0): Boolean = {
    if (sofar >= 100) 
      true else {
        val a = x + spiegel (x)
        if (isPalindrom (a))
          false else
            lychrel (a, sofar + 1) 
      }
  }

  def main (args: Array [String]) =
    for (i <- (1 to 100000)) {
    if (lychrel (i))
      println (i) 
    }
}

SML

von kart0ffelsack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
fun revhelp x = IntInf.fromString(implode(rev(explode(IntInf.toString(x)))));

fun revhelp2(SOME(x)) = x;

fun revInt x = revhelp2(revhelp(x));

fun isPalindrom x = revInt(x) = x;

fun isLychrel (x,0) = true
|    isLychrel (x,y) =   
let
     val erg = x + revInt(x)
in
     not isPalindrom(erg) && isLychrel(erg,y-1)
end;

fun test 0 = []
|    test x =
if isLychrel(x,100) then x::test(x-1) else test(x-1);

test 100000;

Fibonacci (27.02.08)

ASM

von kart0ffelsack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
	    add $a1 $zero 0x00000001
	    add $t2 $zero 0x00000028
	    add $t3 $zero 0x00000002
	    add $s0 $zero 0x10010000
	    add $s1 $zero 0x10010020
	    sw $a0 0($s0)
	    sw $a1 0($s1)
	    add $s2 $zero 0x10010040
 A:    beq $t3 $t2 B
	    lw $a0 0($s0)
	    lw $a1 0($s1)
	    add $a3 $a0 $a1
	    sw $a1 0($s0)
	    sw $a3 0($s1)
	    sw $a3 0($s2)
	    add $s2 $s2 0x00000020
	    add $t3 $t3 0x00000001
	    j A	
 B:    add $a0 $zero 0x00000002
	    div $t2 $t2 $a0
	    add $s3 $s2 0x00000020
 C:    beq $t3 $t2 D
	    l.s $f0 0($s2)
	    sub $s2 $s2 0x00000020
	    l.s $f1 ($s2)
	    sub $s2 $s2 0x00000020
	    div.s $f3 $f0 $f1
	    s.s $f0 ($s3)
	    add $s3 $s3 0x00000020
	    sub $t3 $t3 0x00000001
	    j C
 D:

BASH

von user unknown

1
l=1;r=1; for s in $(seq 1 50); do l=$((l+r)); r=$((r+l)); echo -e $s"\t"$l"\t"$r"\t" $(echo "scale=16; $r/$l" | bc); done

von user unknown

1
echo "scale=16;r=0;l=1;while (i++<100) {r+=l;l+=r;r;l;l/r;}" | bc

von user unknown

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#/bin/bc
#
# fibonacci und Goldener Schnitt
#
scale=16
i=0
r=0
l=1
r
r/l
while (i++<100)
{
        r+=l
        print i, "\t", r, "\t", r/l, "\t"
        l+=r
        print l, "\t", l/r, "\n"
}
print "\n\n"

C

von audax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
int main( void )

{
    double n = 1;
    double m = 1;
    double tmp;
    int i;

    for(i=0; i<100;i++) {
            printf("%d\t%.f\t%f\n", i, n, (n/m));
            tmp = n;
            n = m;
            m = tmp + m;
    }
    return 0;
} 

von Marc 'BlackJack' Rintsch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <gmp.h>

int main(void)
{
    int i;
    mpf_t a, b, tmp, golden_ratio;
    
    mpf_set_default_prec(200);
    mpf_init(a);
    mpf_init_set_ui(b, 1);
    mpf_init(tmp);
    mpf_init(golden_ratio);
    
    for (i = 0; i <= 100; i++) {
        mpf_set(tmp, b);
        mpf_add(b, b, a);
        mpf_set(a, tmp);
        
        mpf_div(golden_ratio, b, a);
        
        gmp_printf("%3d. %21.0Ff %.50Ff\n", i, a, golden_ratio);
    }
    
    mpf_clear(a);
    mpf_clear(b);
    mpf_clear(tmp);
    mpf_clear(golden_ratio);
    return 0;
} 

C++

von Hello World

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <gmpxx.h>
using namespace std;
int main() {
        vector<mpz_class> v(100);
        v[0]=v[1]=1;
        cout << 1 << endl << 1 << endl;
        for(char i=2;i<100;++i) {
                v[i]=v[i-1]+v[i-2];
                cout << v[i] << endl;
        }
        for(char i=1;i<100;++i) {
                cout << mpq_class(v[i],v[i-1]).get_d() << endl;
        }
} 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
typedef unsigned long long u64;
template<u64 x1, u64 x2, u64 y1, u64 y2> struct add {
        const static u64 result2 =
                (x2+y2) & (~(1ULL<<63));
        const static u64 result1 =
                ((x2+y2) & (1ULL<<63) ? 1 : 0) + x1+y1;
};

template<short i> struct fibo {
        const static u64 result2 =
                add<fibo<i-1>::result1,fibo<i-1>::result2,fibo<i-2>::result1,fibo<i-2>::result2>::result2;
        const static u64 result1 =
                add<fibo<i-1>::result1,fibo<i-1>::result2,fibo<i-2>::result1,fibo<i-2>::result2>::result1;
};

template<> struct fibo<0> {
        const static u64 result2 = 0;
        const static u64 result1 = 0;
};
template<> struct fibo<1> {
        const static u64 result2 = 1;
        const static u64 result1 = 0;
};

template<short i> struct fibo_printer {
        static void print() {
                std::cout << "Die " << i << ". Fibonacci-Zahl lautet: "
                          << fibo<i>::result1 << " * 2^63 + "
                          << fibo<i>::result2 << std::endl;
                fibo_printer<i+1>::print();
        }
};
template<> struct fibo_printer<101> {
        static void print() {
                return;
        }
};
int main() {
        fibo_printer<0>::print();
} 

D

von Marc 'BlackJack' Rintsch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import std.stdio;
void main()
{
    real a, b, tmp;
    a = b = 1;
    for (uint i = 0; i <= 100; i++) {
        writef("%3d. %21.0f %.50f\n", i, a, b / a);
        tmp = b;
        b += a;
        a = tmp;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import std.stdio;

static const ulong MAX = 10000000000000000000_UL;

template add(ulong lo1, ulong hi1, ulong lo2, ulong hi2)
{
    const ulong low = lo1 + lo2 % MAX;
    const ulong high = hi1 + hi2 + (lo1 + lo2 >= MAX ? 1 : 0);
}

template F(uint n)
{
    static if (n == 0) {
        const ulong low = 0;
        const ulong high = 0;
    } else static if (n == 1) {
        const ulong low = 1;
        const ulong high = 0;
    } else {
        alias F!(n - 1) F_1;
        alias F!(n - 2) F_2;
        mixin add!(F_1.low, F_1.high, F_2.low, F_2.high);
    }
}

template Fib(uint n, uint i = 0)
{
    static if (i <= n) {
        void print()
        {
            alias F!(i) F_i;
            static if (F_i.high == 0) {
                writef("%3d. %d\n", i, F_i.low);
            } else {
                writef("%3d. %d%020d\n", i, F_i.high, F_i.low);
            }
            Fib!(n, i + 1).print();
        }
    } else {
        void print() {}
    }
}

void main()
{
    Fib!(100).print();
}

Erlang

von radoe2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
-module(fib2).
-export([fib/1,start/1]).
fib(N) ->
    fib(1,1,N).
fib(F1,_,1) ->
    io:format("~w~n", [F1]);
fib(F1,F2,N) ->
    FN = F1+F2,
    fib(F2,FN,N-1).
%%%
start([H|_]) ->
    N= list_to_integer(atom_to_list(H)),
    io:format("fib(~w)=~n", [N]),
    fib(N),
    init:stop().

Fortran

von GerritK

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
program fibo
  implicit none
  double precision, dimension(0:99)    :: f = 0, g = 0
  integer :: n = 0
  f(0) = 0
  f(1) = 1
  do n=0,99
    f(n) = 1.0/sqrt(5.0) * ( ((1.0+sqrt(5.0))/2.0)**n - ((1.0-sqrt(5.0))/2.0)**n )
  enddo
  do n=0,98
    if (f(n) == 0) then
      g(n) = 0.0
    else
      g(n) = f(n+1)/f(n)
    endif
  enddo
  print'(I3,2X,F30.1,2X,F10.8)', (n+1, f(n), g(n), n=0,99)
end program

Haskell

von Marc 'BlackJack' Rintsch

1
2
3
4
fibonacci = fib 1 1
    where fib a b = a : fib b (a+b)
f a b = show a ++ " " ++ show (fromIntegral b / fromIntegral a)
main = mapM_ putStrLn $ take 100 $ zipWith f fibonacci (tail fibonacci)

von Morningrise

1
2
3
module Main where
fib  = 0 : 1 : zipWith (+) fib (tail fib)
main = print [ ([fp,f], f/fp) | n <- [2..101], let fp =  fib !! (n-1), let f = fib !! n]

Java

von Greebo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.math.*;
public class Fib2 {
   public static void main(String[] args) {
      if (args.length != 2)
         System.exit(-1);
      try {
         int max = Integer.parseInt(args[0]);
         int precission = Integer.parseInt(args[1]);
         int mlen = Integer.toString(max - 1).length();
         int flen = fibIter(max).toString().length();
         BigDecimal n1 = BigDecimal.ZERO;
	 BigDecimal n2 = BigDecimal.ZERO;
         for (int i = 1; i < max; ++i) {
            n1 = n2;
            n2 = fibIter(i);
            String ratio = n1.intValue() == 0 ? "infinity" : n2.divide(n1,
                  precission, RoundingMode.HALF_UP).toString();
            System.out.format("f(%" + mlen + "d) = %" + flen + "s, f(%"
                  + mlen + "d)/f(%" + mlen + "d) ~= %s%n", i, n2, i,
                  i - 1, ratio);
         }
      } catch (NumberFormatException e) {
         System.err.format("Invalid command line parameter: %s or %s",
               args[0], args[1]);
         System.exit(-1);
      } catch (IllegalArgumentException e) {
         System.err.format("Invalid command line parameter: %s or %s",
               args[0], args[1]);
         System.exit(-1);
      }
   }
   public static BigDecimal fibIter(int i) {
      if (i < 0)
         throw new IllegalArgumentException();
      if (i < 2)
         return new BigDecimal(Integer.toString(i));
      BigDecimal a = BigDecimal.ZERO;
      BigDecimal b = BigDecimal.ONE;
      BigDecimal c = a.add(b);
      for (; i > 2; --i) {
         a = b;
         b = c;
         c = a.add(b);
      }
      return c;
   }
}

Ook

von kart0ffelsack

Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook! Ook? Ook! Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook. Ook! Ook? Ook. Ook? Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook! Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook! Ook. Ook? Ook! Ook. Ook. Ook? Ook. Ook? Ook! Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook? Ook! Ook? Ook? Ook. Ook? Ook. Ook. Ook. Ook. Ook? Ook. Ook. Ook. Ook? Ook! Ook! Ook? Ook! Ook? Ook. Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook! Ook? Ook! Ook! Ook? Ook! Ook. Ook? Ook. Ook. Ook. Ook? Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook. Ook! Ook! Ook! Ook? Ook. Ook? Ook. Ook. Ook? Ook. Ook! Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook? Ook! Ook. Ook. Ook. Ook? Ook. Ook? Ook. Ook? Ook? Ook! Ook? Ook. Ook? Ook. Ook? Ook. Ook? Ook!

Perl

von Sid Burn

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/perl (-)
# Core Module
use strict;
use warnings;
use utf8;
use open ':utf8';
use open ':std';
use Memoize;
sub fib {
    my ( $number ) = @_;
    return 1 if $number <= 1;
    return fib($number-1) + fib($number-2);
}
memoize('fib');
for my $i ( 1 .. 100 ) {
    printf "%.0f / %.0f = %.14f\n", fib($i), fib($i-1), fib($i) / fib($i-1);
}

von e1bart0

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env perl (-)
##############################
# File: fib.pl
# Copyright (C) by Kai Wilker <kai.wilker@googlemail.com>
# 2008-02-27
##############################
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
use strict;
use warnings;
my @fibonaccis = (1, 1);
my @schnitt;
push @fibonaccis, $fibonaccis[-1] + $fibonaccis[ @fibonaccis - 2 ] for 1..99;
push @schnitt, $fibonaccis[ $_ + 1 ] / $fibonaccis[$_] for 0..99;
print "Fibonacci-Zahlen:\n\n";
printf "%.0f\n", $_ for @fibonaccis;
print "\n\n\nGoldener-Schnitt:\n\n";
printf "%.14f\n", $_ for @schnitt;

Python

von Marc 'BlackJack' Rintsch

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/usr/bin/env python
from __future__ import division
from itertools import islice
def fib_and_golden_ratio():
    a = b = 1
    while True:
        yield (a, b / a)
        a, b = b, a + b
def main():
    for values in islice(fib_and_golden_ratio(), 100):
        print '%d, %.50f' % values
if __name__ == '__main__':
    main()

von audax

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from __future__ import division
from itertools import islice
def fibgen():
    n = m = 1
    while True:
        yield n, m
        n, m = m, n+m
print '\n'.join(
    ("%d\t%d\t%f" % (c, new, new/old) for
        c, (new, old) in enumerate(islice(fibgen(), 100))))

von Prinz Igor

1
2
3
4
5
6
7
8
9
f1 = 0
f2 = 1
print f1
print f2
for i in range(98):
  f3 = f1+f2
  print '%d %.50f' % (f3,float(f3)/f2)
  f1 = f2
  f2 = f3

Ruby

von Adna rim

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#!/usr/bin/env ruby (-)
fibonacci=[1,1]
gold_schnitt=[]
while fibonacci.size <= 100
        gold_schnitt<<fibonacci[-1].to_f/fibonacci[-2].to_f
        fibonacci<<fibonacci[-1]+fibonacci[-2]
end
printf("\nFibonacci-Zahlen: ")
fibonacci.each {|num| printf('%s ',num)}
printf("\n\nGoldener-Schnitt: ")
gold_schnitt.each {|num| printf('%s ',num)}
puts

SML

von kart0ffelsack

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
fun fib 0 = 0
|    fib 1 = 1
|    fib n = fib(n-1) + fib(n-2);
fun fiblist [] = []
|    fiblist (x::xl) = fib(x)::fiblist(xl);
fun makelist 0 = [0]
|    makelist x = makelist(x-1)@[x];
fun golden [] = []
|    golden (x::[]) = []
|    golden (x::y::xl) = real(y)/real(x)::golden(xl);
fiblist(makelist(100));
golden(fiblist(makelist(100)));

Diese Revision wurde am 11. Juni 2024 12:03 von Marc_BlackJack_Rintsch erstellt.
Die folgenden Schlagworte wurden dem Artikel zugewiesen: Programmierung