Solved ProjectEuler/014: php, ruby, c
This commit is contained in:
27
ProjectEuler/014/desc.yml
Normal file
27
ProjectEuler/014/desc.yml
Normal file
@ -0,0 +1,27 @@
|
||||
title: Find the longest sequence using a starting number under one million.
|
||||
url: http://projecteuler.net/problem=14
|
||||
|
||||
desc: |
|
||||
The following iterative sequence is defined for the set of positive integers:
|
||||
n -> n/2 (n is even)
|
||||
n -> 3n + 1 (n is odd)
|
||||
Using the rule above and starting with 13, we generate the following sequence:
|
||||
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
|
||||
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
|
||||
|
||||
Which starting number, under one million, produces the longest chain?
|
||||
NOTE: Once the chain starts the terms are allowed to go above one million.
|
||||
|
||||
solution: |
|
||||
Bruteforce
|
||||
|
||||
solutions:
|
||||
solve.php:
|
||||
desc: Basic solution
|
||||
language: php
|
||||
solve.rb:
|
||||
desc: Basic solution
|
||||
language: ruby
|
||||
solve.c:
|
||||
desc: ANSI C compiled with TCC
|
||||
language: c
|
34
ProjectEuler/014/solve.c
Normal file
34
ProjectEuler/014/solve.c
Normal file
@ -0,0 +1,34 @@
|
||||
#define MAX 1000000-1
|
||||
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
|
||||
int main( )
|
||||
{
|
||||
unsigned int max_steps = 0;
|
||||
unsigned int max_start;
|
||||
|
||||
unsigned int test;
|
||||
|
||||
unsigned long ctest;
|
||||
unsigned int steps;
|
||||
|
||||
for(test = MAX; test > 1 ; test--)
|
||||
{
|
||||
|
||||
ctest = test;
|
||||
steps = 1;
|
||||
while(ctest != 1)
|
||||
{
|
||||
ctest = ( ctest % 2 ) ? ctest * 3 + 1 : ctest / 2;
|
||||
steps++;
|
||||
}
|
||||
if(steps > max_steps)
|
||||
{
|
||||
max_start = test;
|
||||
max_steps = steps;
|
||||
}
|
||||
|
||||
}
|
||||
printf( "%lu", max_start );
|
||||
}
|
13
ProjectEuler/014/solve.php
Normal file
13
ProjectEuler/014/solve.php
Normal file
@ -0,0 +1,13 @@
|
||||
<?php
|
||||
$max_steps = 0;
|
||||
for($test=999999;$test>1;$test--) {
|
||||
$ctest = $test;
|
||||
$steps = 1;
|
||||
while($ctest != 1) {
|
||||
$ctest = ($ctest % 2) ? $ctest*3+1 : $ctest/2;
|
||||
$steps++;
|
||||
}
|
||||
|
||||
if($steps > $max_steps) { $max_start = $test; $max_steps = $steps;}
|
||||
}
|
||||
echo $max_start;
|
18
ProjectEuler/014/solve.rb
Normal file
18
ProjectEuler/014/solve.rb
Normal file
@ -0,0 +1,18 @@
|
||||
max_start = 0
|
||||
max_steps = 0
|
||||
test = 1
|
||||
|
||||
while(test < 1000000)
|
||||
ctest = test
|
||||
steps = 1
|
||||
while(ctest != 1)
|
||||
ctest = ( ctest % 2 != 0) ? ctest * 3 + 1 : ctest / 2
|
||||
steps += 1
|
||||
end
|
||||
if(steps > max_steps)
|
||||
max_start = test
|
||||
max_steps = steps
|
||||
end
|
||||
test += 1
|
||||
end
|
||||
puts max_start
|
Reference in New Issue
Block a user