[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/20034/edit).
Closed 6 years ago.
[Improve this question](/posts/20034/edit) 
**Introduction**: Deep Thought calculated *The answer to life the universe and everything* in a period of 7.5 million years, the solution was **`42`**.
Write a program in any programming language that takes approx `75` seconds to calculate, starting from whatever you want, and output the number **`42`**.
N.B. The number `42` must be calculated somehow (random numbers, whatever you prefer), not just hard-coded in your script. 
As suggested, you can't use `sleep` or equivalent functions. Be inventive.
  
[Answer]
This takes about 75s on a raspberry pi overclocked to 1GHz
```
#!/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
```
It works because:
> 
> 42 is the only known value that is the number of sets of four
>  distinct positive integers a,b,c,d, each less than the value itself,
>  such that ab-cd, ac-bd, and ad-bc are each multiples of the value.
>  Whether there are other values remains an open question
> 
> 
> 
<http://www.mathpages.com/home/kmath255.htm>
[Answer]
## Python 2.7
To answer the question, one must *know* the question - and the question is:
> 
> What do you get when you multiply six by nine? Thanks to TRiG for the correction
> 
> 
> 
So **Deep Thought** relies on the [handy use of base 13](https://en.wikipedia.org/wiki/Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#The_number_42):
> 
> 613 x 913 = 4213 
> 
> 
> 
We import our constants:
```
from random import randrange as scrabbleBag, randint
from datetime import datetime,timedelta
life,universe,everything,nothing=6,9,1,-3
endOfTheUniverse = 80
```
We also define our earth-things, being a **bag of scrabble tiles**, **Arthur** (a predictable albeit it slightly odd, computer of sorts), **Trillian** (our rational heroine), 
```
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)))
```
We introduce **Zaphod** - a random sort, who eventually runs out of steam as we near the `endOfTheUniverse`.
```
zaphod = lambda : not(randint(0,(endOfTheUniverse-(datetime.now() - start).seconds)**3))
```
And **Marvin the Paranoid Android**, whose positive attitude could stop any party:
```
marvin = lambda : endOfTheUniverse<(datetime.now() - start).seconds
```
And we continue to run these 4 characters through the mix until they compute ***it***:
```
while answer is not life * universe * everything:
  rack = sum(tile(i) for i in range(7))
  answer = (zaphod or marvin) and arthur(rack)
print trillian(answer)
```
## The complete `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
answer = None
while answer is not life * universe * everything:
  rack = sum(tile(i) for i in range(7))
  answer = (zaphod() or marvin()) and arthur(rack)
print trillian(answer)
```
This should finish somewhere around the 75 second mark, definitely finishing by 80 seconds. Sometimes earlier to to Zaphods *Infinite Improbability Drive*.
[Answer]
# DOS Batch — the answer to life, the Universe and everything
Thanks to mynameiscoffey for his simplification!
Save as `answer.bat`:
```
@ ping 127.0.0.1 -n 76 >nul && @ echo %~z0
```
Then run it, and wait 75 seconds:
```
> answer
42
```
[Answer]
# Bash (OS X)
This could probably be ported to other systems without too much trouble. Replace `say` with whatever you're using as a text-to-speech command line utility. The `-f` option takes input from a named file.
With a bit of luck, it might even output the correct number :-)
This takes almost exactly 1 minute 15 seconds to run on my system (OS X 10.5).
```
#!/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"
```
[Answer]
## MATLAB
This is a tough one. Since we do not really know the question, the only viable method of getting the answer is by means of a global optimisation method. In this case I opted for the [simulated annealing](http://en.wikipedia.org/wiki/Simulated_annealing) method, since this one has given me nice answers to tough questions before.
All this code is doing is looking for the optimal value of a function which input is life itself. And the amazing thing is that it works. So, did I just validate Deep Thought?
```
tic;
the_answer=round(simulannealbnd(@(life)abs(3.7376696-log(life)),140489, ...
           -inf,inf,saoptimset('MaxFunEvals',10^16)))
toc;
```
Output:
```
the_answer =
    42
Elapsed time is 74.892428 seconds.
```
[Answer]
# C - 1089 bytes
```
#include <time.h>
#include <stdio.h>
int answer(int the)
{
   int to = 0;
   while (the != 0) {
      to *= 10;
      to += the%10;
      the /= 10;
   }
   return to;
}
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;
    // get inverse answer
    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();}
    universe = answer(life);
    everything = optimism(life<universe?life-universe:universe-life);
    printf("%d\n", (answer(everything)+everything+3)/26);
    return 0;
}
```
---
## Compressed:
```
#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;
}
```
[Answer]
# Ruby
```
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}"
```
Output on my machine:
```
42
Took 123 seconds; seed was 3771996
```
This abuses the RNG. ;)
[Answer]
# 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);
}
```
[Answer]
## JavaScript - Finding "the answer to life and everything" by solving an equation
Let's have a look at this equation :
```
1 / p  +  1 / q  +  1 / r  =  1 / 2
```
There is many solutions, but if you want `r` to be as big as possible and `p`, `q` and `r` to be naturals there is only two solutions :
`1/3 + 1/7 + 1/42 = 1/2` and `1/7 + 1/3 + 1/42 = 1/2`
with `p <= q <= r`, there is only one solution and `r` always equal to `42`
What is the most (in)efficient way to solve a equation ?
By trying all possibles values !
Here is the code :
```
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;                
        }
    }
}
```
How much time will it take ? To be honest, I do not know because I have not been able to run it to the end.
However, you can try with small `n` values (it has to be bigger or equal to `42`) and you will get correct result. For small values such as `n = 2000`, it takes almost one minute on my laptop. So i guess with big values given in the example it will take days, weeks, or even years !!!
**Finding the solution in approximately 75 seconds :**
One requirement from initial question is it should take approximately 75 sec to execute. One way to achieve this is to automatically adjust the complexity of the algorithm over the time :
```
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++;
        }
    }
}
```
How it works (for the curious) : it checks how many iterations have been done in one second, then multiply this by 74 and adjust `n` to match that value. eg : if it take one second to do 500 iterations, it will take 10 seconds to do 5000 iterations. Note that it multiply by 74 not 75 because we already spent one second for "benchmarking".
[source and credits for math](http://www.math.ucr.edu/home/baez/42.html)
[Answer]
C# - 151 Characters
```
class P
{
   static void Main()
   {
      var w = new System.Diagnostics.Stopwatch();
      w.Start();
      while (w.ElapsedMilliseconds < 75000);
      System.Console.Write((int)'*');
   }
}
```
[Answer]
**C++**
Calculates the [partitions](http://en.wikipedia.org/wiki/Partition_%28number_theory%29) of [10](http://www.wolframalpha.com/input/?i=partition%2010) via a rather inefficient method. Took 130s to run in a Release build on my system but someone with a sufficiently fast PC should be able to run it in ~75s...
```
#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;
}
```
[Answer]
## Javascript
This will take a while to alert something ... but it's worth since it will show you The answer to life the universe and everything!
```
var x = 0, b = document.body.children[0];
var theAnswer = function(){
  b.textContent = ++x;
  if(x == 125774) alert(Math.pow(x, 1/Math.PI)).toFixed(0);  
  else setTimeout(theAnswer);
};
theAnswer();
```
[Demo](http://codepen.io/rafaelcastrocouto/pen/HKurF "Codepen") 
[Answer]
# Python
Sometimes an answer is only clear at the very end of a calculation, but aspects of it are visible before termination.
And little known is the sequence of inputs Deep Thought was seeded with: 
271, 329, 322, 488, 79, 15, 60, 1, 9
Hence:
```
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]))
```
Et voila - the answer is provided after 75 seconds.
[Answer]
## Assembly (linked by gcc)
On a sufficiently slow computer (CPU speed ~2Hz) this should take around 75 seconds to run:
```
  .globl        main
main:
  movl  $52, %edx
  movl  $0, %edi
l4:
  addl $1, %edi
  cmp %edx, %edi
  jl l4
  call  putchar
  movl  $50, %edx
  movl  $0, %edi
l2:
  addl $1, %edi
  cmp %edx, %edi
  jl l2
  call  putchar
  movl  $10, %edx
  movl  $0, %edi
ln:
  addl $1, %edi
  cmp %edx, %edi
  jl ln
  call  putchar
  ret
```
[Answer]
# Bash and Linux utils:
```
#!/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 is listening carefully all the way through the calculation.
[Answer]
# Java (227 characters)
Who says that bitwise manipulations are not fun? Or that java can't be confusing?  
We loop for 75 seconds and then boom the answer.
```
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);}}
```
Ungolfed
```
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);
    }
}
```
[Answer]
# PureBasic
In keeping with the fact that different hardware will produce different results, there is no fixed answer for this. I am using an elapsed time function so I know when to stop calculating.
Basically, it will calculate the largest two prime numbers when subtracted is 42
Faster your machine, the larger the primes will be :-)
```
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("Answer: ")
Print(Str(FoundFigure2 - FoundFigure1))
Input()
```
[Answer]
***MeatSpace***
Pace off a distance which takes approximately 70/4 seconds for your `servant^H^H^H^Hcomputer` (it could be human, dog, or anything that can pick up numeral tiles) to walk. Place a large numeral `4` and a large numeral `2` there. Place your `computer` to the output point. Start the timer, have it walk to the numeral depot and bring back one number at a time.
I allocated 5 seconds to pick them up and put them down.
[Answer]
**Another C# Example**
```
using System;
using System.Threading;
namespace FourtyTwo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime then = DateTime.Now;
            Thread.Sleep(42000);
            DateTime now = DateTime.Now;
            TimeSpan t = now - then;
            Console.WriteLine(t.Seconds);
        }
    }
}
```
[Answer]
# Ruby
> 
> A program to add (0.56) power n for 75 times. Value of `n is 1`
> 
> 
> Where `n=1` should be obtained from any form of `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
```
Using ruby time difference I've verified the execution time which is approx `75.014267762`
[Answer]
**PHP**
```
<?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);
?>
```
This is as close as I'm getting tonight. Running it at [tecbrat.com](http://www.tecbrat.com/test1.php), an old IBM NetVista P4 running Ubuntu 10.04, showed 69 seconds and 78 seconds on my last 2 runs.
[Answer]
# JavaScript (Bitwise obfuscation) (not bad for 136 bytes!)
It may be seen as a bit on the cheaty side, but the functions were meticulously thought out, bearing in mind that the 75000ms value would be calculated prior to the functions used to calculate 42. It's quite poetic when you look at it, really :)
`setTimeout("alert($=((_=_=>(_<<-~-~[])|-~[])(_(-~[])))<<-~[])",($=$=>$<<-~-~-~[]|-~[])((_=_=>_<<-~[]|-~[])(_(_(_($($($(-~[]))))))))^-~[])`
[Answer]
I am not too good with this kind of stuff. I'm an app developer but I've never had any training in C and I mostly make apps that grab stuff from servers and make the information look pretty... 
I have no idea if this will work and there's a bit of extra code in there because it's in a iphone app and I display a progress hud and an alert view when 42 has been reached:
```
#import "ViewController.h"
#import "MBProgressHUD.h"
@interface ViewController ()
@property (nonatomic, retain) MBProgressHUD * hud;
-(IBAction)answer:(id)sender;
@end
int number;
int initialCounter;
@implementation ViewController
@synthesize hud;
-(IBAction)answer:(id)sender
{
    hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"Calculating";
    [self calculate];
    number = arc4random();
}
-(void)calculate
{
    int random = arc4random();
    if (number == 42){
        hud.hidden = YES;
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Complete!"
                                                          message:@"The answer is 42."
                                                         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
```
]