# 生命，宇宙和一切的答案[关闭]

43

6

30

Fozzedout 2014年

7

Josh

3
timeapi.org/utc/now。这似乎是使用类似您的语言的睡眠库的最佳选择。这仅需几个http请求。
Cruncher

3

53

``````#!/usr/bin/env python
from itertools import product, count

for n in count(1):
i = 0
for a, b, c, d in product(range(n), repeat=4):
if a > b > c > d > 0 == (a*b-c*d)%n == (a*c-b*d)%n == (a*d-b*c)%n:
i += 1
if i == n:
break
print i
``````

http://www.mathpages.com/home/kmath255.htm

12

Assaf G. 2014年

1
@FezVrasta，因为最后一行不见了。h！
gnibbler 2014年

2

Tomas

1

2014年

1

agweber 2014年

43

## Python 2.7

6 13 x 9 13 = 42 13

``````from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80
``````

``````tile = lambda i: scrabbleBag(26)
arthur = lambda i: int(`i`,life+universe+everything+nothing)
trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing)))
``````

``````zaphod = lambda : not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))
``````

``````marvin = lambda : endOfTheUniverse<(datetime.now() - start).seconds
``````

``````while answer is not life * universe * everything:
rack = sum(tile(i) for i in range(7))
answer = (zaphod or marvin) and arthur(rack)
``````

## 完整的`deepthought.py`：

``````from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80

tile = lambda i: scrabbleBag(26)
arthur = lambda i: int(`i`,life+universe+everything+nothing)
trillian = lambda i: ''.join(map(str,divmod(i,life+universe+everything+nothing)))

start = datetime.now()

zaphod = lambda: not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))
marvin = lambda: endOfTheUniverse<(datetime.now() - start).seconds

while answer is not life * universe * everything:
rack = sum(tile(i) for i in range(7))
answer = (zaphod() or marvin()) and arthur(rack)
``````

1

Fez Vrasta 2014年

1
@FezVrasta对不起，我不小心添加了一些错误的代码。现在修复它，应该可以工作。

4

8
“我可能会感到遗憾，但我不会在基础13中开玩笑。” -DNA
MikeTheLiar 2014年

3

13

# DOS Batch –生活，宇宙和一切的答案

``````@ ping 127.0.0.1 -n 76 >nul && @ echo %~z0
``````

``````> answer
42
``````

Fez Vrasta 2014年

Fez Vrasta，2014年

Fez Vrasta 2014年

2

mynameiscoffey 2014年

10

# 重击（OS X）

``````#!/bin/bash
grep -E '^life|universe|and.everything|[ultimate]question\$' /usr/share/dict/words | sed 's/\$/,/' | nl > "\$TMPDIR/deepthought"
say -v Alex -f "\$TMPDIR/deepthought"
nw=`cat \$TMPDIR/deepthought | wc -l`
say -v Alex "The answer, to the ultimate question, is: \$nw"
echo \$nw
rm "\$TMPDIR/deepthought"
``````

10

## 的MATLAB

``````tic;

-inf,inf,saoptimset('MaxFunEvals',10^16)))
toc;
``````

``````the_answer =

42

Elapsed time is 74.892428 seconds.
``````

5

# C-1089字节

``````#include <time.h>
#include <stdio.h>

{
int to = 0;

while (the != 0) {
to *= 10;
to += the%10;
the /= 10;
}
}

int optimism(int the)
{
return abs(the);
}

int getRandomNumber()
{
return 4; // chosen by fair dice roll.
// guaranteed to be random.
}

int main()
{
// initialize
int life = getRandomNumber(), universe, everything;

int question = clock();
while (clock()-question < CLOCKS_PER_SEC*75) {
life += getRandomNumber();
}
life = optimism(life); // optimism is the best way to see life
life %= 1000;

// avoids unwanted race conditions with the answer by "Lego Stormtroopr"
if (life<100 || life>997) {life -= getRandomNumber()*100;}
if (optimism(life/100%10 - life%10) < 2) {life += getRandomNumber();}
everything = optimism(life<universe?life-universe:universe-life);

return 0;
}
``````

## 压缩后：

``````#include <time.h>

int f(int d) {
int e = 0;
while (d != 0) e = e*10+d%10, d /= 10;
return e;
}

int main() {
int a = 4, b, c, d = clock();
while (clock()-d < CLOCKS_PER_SEC*75) a += 4;
a = abs(a)%1000;
a -= a<100||a>997?400:0;
a += abs(a/100%10-a%10)<2?4:0;
b = f(a);
c = abs(a<b?a-b:b-a);
return (f(c)+c+3)/26;
}
``````

4

# 红宝石

``````t = Time.new.to_i
n = 0
loop{
break if Random.new(n).rand(2000000) == Random.new(374076).rand(1000000)
n += 1
}
puts Random.new(n).rand(2000000)
puts "Took #{Time.new.to_i - t} seconds; seed was #{n}"
``````

``````42
Took 123 seconds; seed was 3771996
``````

1

1
@Arlaud它运行了370万次循环迭代，每次循环生成2个随机数！从技术上讲，如果您有一些超级计算机，它可能会更快，但是对于任何合理的硬件，它至少需要75秒钟，而且我不想感到无聊并使用睡眠或时间方法。

4

# C

``````#include <stdio.h>
#include <time.h>

int i, j;

int main() {
i = clock();
while(clock() - i < 75 * CLOCKS_PER_SEC);
for(i = j = 0 ; i < 48 ; i++)
j += "The answer to Life, the Universe, and everything"[i];
printf("%i", j % 157);
}
``````

2

mniip 2014年

@ArlaudPierre 我提交答案时是代码高尔夫。无论如何，现在已修复。
Oberon 2014年

4

## JavaScript-通过求解方程式找到“生命和一切的答案”

``````1 / p  +  1 / q  +  1 / r  =  1 / 2
``````

`1/3 + 1/7 + 1/42 = 1/2``1/7 + 1/3 + 1/42 = 1/2`

``````var n = Math.pow(2, 32);
for (var i = 1; i <= n; i++)
{
for (var j = 1; j <= n;  j++)
{
for (var k = 1; k <= n; k++)
{
if ((1 / i + 1 / j + 1 / k) == 1 / 2)
throw k;
}
}
}
``````

``````var now = new Date().getTime();
var iterations = 0;
var n = Math.pow(2, 32);
for (var i = 1; i <= n; i++)
{
for (var j = 1; j <= n; j++)
{
for (var k = 1; k <= n; k++)
{
if ((1 / i + 1 / j + 1 / k) == 1 / 2)
throw k;

if (new Date().getTime() - now > 1000) //one second has elapsed
{
now *= 2; //never wanna see you again
n = 42;   //this is the minimum
while(3 * n * n + 7 * n + 42 < iterations * 74) n++;
i = j = k = 0; //reset
}
iterations++;
}
}
}
``````

2

C＃-151个字符

``````class P
{
static void Main()
{
var w = new System.Diagnostics.Stopwatch();
w.Start();
while (w.ElapsedMilliseconds < 75000);
System.Console.Write((int)'*');
}
}
``````

valdetero 2014年

Merin Nakarmi 2014年

valdetero 2014年

1

microbian

2

C ++

``````#include <algorithm>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>

using namespace std;

bool NextPermutationWithRepetition(vector<int>& perm, int n) {
int carry = 1;
auto it = begin(perm);
while (it != end(perm) && carry) {
++*it;
carry = (*it - 1) / n;
*it = ((*it - 1) % n) + 1;
++it;
}
if (carry) {
if (perm.size() == n) return false;
perm.push_back(carry);
}
return true;
}

int main() {
vector<int> perm;
set<vector<int>> uniquePartitions;
const int n = 10;
while (NextPermutationWithRepetition(perm, n)) {
if (accumulate(begin(perm), end(perm), 0) == n)  {
auto sortedPerm = perm;
sort(begin(sortedPerm), end(sortedPerm));
uniquePartitions.insert(sortedPerm);
}
}
cout << uniquePartitions.size() << endl;
}
``````

2

## Java脚本

``````var x = 0, b = document.body.children[0];
b.textContent = ++x;
};
``````

1

Fabinout 2014年

rafaelcastrocouto 2014年

2

# 蟒蛇

271、329、322、488、79、15、60、1、9

``````from datetime import datetime
n = datetime.now
o = n().second

def bs(x,n,t,f):
return ([t]+bs(x-2**(n-1),n-1,t,f) if x>=2**(n-1) else [f]+bs(x,n-1,t,f)) if n>0 else []

u = [271,329,322,488,79,15,60,1,9,'#',' ','',]
for i, g in enumerate(u[:5]):
while n().second!=(o+(i+u[7])*u[5])%u[6]:
pass # the dice
print u[11].join(bs(g,*u[8:11]))
``````

2

## 汇编（由gcc链接）

``````  .globl        main
main:
movl  \$52, %edx
movl  \$0, %edi
l4:
cmp %edx, %edi
jl l4
call  putchar
movl  \$50, %edx
movl  \$0, %edi
l2:
cmp %edx, %edi
jl l2
call  putchar
movl  \$10, %edx
movl  \$0, %edi
ln:
cmp %edx, %edi
jl ln
call  putchar
ret
``````

1

# Bash和Linux实用程序：

``````#!/bin/bash

if [ \$(uname) == "Linux" ]; then
: \$(arecord -q | head -c 600000)
man -s4 random | head -n1 | tr -d ' ' | wc -c
else
echo "Deep Thought didn't run \$(uname)"
fi
``````

Deep Thought在计算过程中一直在认真听取。

1

# Java（227个字符）

``````public class T{public static void main(String[]b){long d=(1<<16^1<<13^1<<10^31<<3);long t=System.currentTimeMillis();long e=t+d;for(;e>System.currentTimeMillis();){}d=d%((((d&~(1<<16))>>7)^(1<<4))^1<<2);System.out.println(d);}}
``````

``````public class T
{
public static void main(String[] b)
{
long d = (1 << 16 ^ 1 << 13 ^ 1 << 10 ^ 31 << 3);
long t = System.currentTimeMillis();
long e = t + d;
for (; e > System.currentTimeMillis();){}
d = d % ((((d & ~(1 << 16)) >> 7) ^ (1 << 4)) ^ 1 << 2);
System.out.println(d);
}
}
``````

0

# PureBasic

``````OpenConsole()

sw = ElapsedMilliseconds()
FoundFigure1 = 0
FoundFigure2 = 0

PreviousPrime = 1

For i = 3 To 10000000000 Step 2
PrimeFound = #True
For j = 2 To i-1
If i % j = 0
PrimeFound = #False
Break
EndIf
Next
If PrimeFound = #True
If i - PreviousPrime = 41+1
FoundFigure1 = PreviousPrime
FoundFigure2 = i
EndIf

PreviousPrime = i
EndIf

If ElapsedMilliseconds() - sw > 75000
Break
EndIf
Next

Print(Str(FoundFigure2 - FoundFigure1))
Input()
``````

0

0

``````using System;

namespace FourtyTwo
{
class Program
{
static void Main(string[] args)
{
DateTime then = DateTime.Now;
DateTime now = DateTime.Now;
TimeSpan t = now - then;
Console.WriteLine(t.Seconds);
}
}
}
``````

1

Fez Vrasta 2014年

0

# 红宝石

`n=1`应不受任何形式的获得`Time diffrence`

``````def solve
a=0.56
i=0
t1=Time.now
while(i < 75)
t1 = Time.now
while((b=Time.now-t1) < 1.0)
end
a += 0.56 ** b.to_i
i += 1
end
a.to_i
end

puts solve
``````

0

``````<?php
set_time_limit(80);
ini_set('max_execution_time', 80);
//\$start=time();
\$count=0;
do{
\$rand=rand(0,(75000000/40+2));
\$rand=rand(0,\$rand);
if((\$rand==42 || \$rand==75-42 || \$rand== floor(75/42)) && (!rand(0,(4*2)))
){
\$count++;
}
}while(\$count!=42);
echo \$count;
//echo '<br>elapsed time is '.(time()-\$start);
?>
``````

0

# JavaScript（按位混淆）（136个字节还不错！）

`setTimeout("alert(\$=((_=_=>(_<<-~-~[])|-~[])(_(-~[])))<<-~[])",(\$=\$=>\$<<-~-~-~[]|-~[])((_=_=>_<<-~[]|-~[])(_(_(_(\$(\$(\$(-~[]))))))))^-~[])`

rafaelcastrocouto 2014年

WallyWest

rafaelcastrocouto 2014年

1
@rafaelcastrocouto啊，可悲的是，用于定义每个语句中的两个功能的粗箭头符号仅适用于Firefox 22及更高版本...
WallyWest

rafaelcastrocouto 2014年

0

``````#import "ViewController.h"
#import "MBProgressHUD.h"

@interface ViewController ()

@property (nonatomic, retain) MBProgressHUD * hud;

@end

int number;
int initialCounter;

@implementation ViewController
@synthesize hud;

{
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = @"Calculating";

[self calculate];

number = arc4random();
}

-(void)calculate
{

int random = arc4random();

if (number == 42){
hud.hidden = YES;
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];

[message show];
}

else if(number<42){
number = number + random;
dispatch_async(dispatch_get_main_queue(), ^{
[self calculate];
});
}

else if(number>42){
number = number - random;
dispatch_async(dispatch_get_main_queue(), ^{
[self calculate];
});
}
}

@end
``````