Archive

Posts Tagged ‘Micro guide’

Adding numbers as strings

September 18th, 2009

Introduction

Today i ran into the problem of not being able to operate with numbers larger than a 1024-bit signed integer, equilavant to 2^1023. I wanted to be able to add two numbers in this size range, providing a number bigger than this barrier. So i wrote a script, that made it possible to do this, by using a method analouge to how you’d add large numbers on a piece of paper: i used strings, where I added each element in each string with each other.
The code is fairly simple, and there’s plenty of comments in it, so I’ll just post it as-is.

The code

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
<?php
function add_as_string($a,$b){
	// Produce an error if either $a or $b is not a string.
	if(!is_string($a) || !is_string($b)){
		return "At least one of the provided numbers was not a string!";
	}
 
	// Finds the length of $a or $b, determined by which of $a and $b is the longest string.
	$length = strlen($a)>strlen($b)?strlen($a):strlen($b);
 
	// Zero-pads the strings if neccesary.
	$a = sprintf("%0{$length}s", $a);
	$b = sprintf("%0{$length}s", $b);
 
	// Here the actual addition takes place. Note that it does the addition "backwards".
	for($x=$length-1;$x>=0;$x--){
		$c[$x] += $a[$x]+$b[$x];
		if($c[$x] >= 10){
			$c[$x-1] += 1;
			$c[$x] -= 10;
		}
	}
	$c = array_reverse($c); // Reverse the array containing the addition numbers.
 
	// Puts all the numbers in $c into a string.
	foreach($c as $number){
		$result .= strval($number);
	}
 
	return $result;
}
 
$a = pow(2,1023); // the highest value php can give me. (corresponds to the maximum value of a 1024-bit signed integer)
$a = sprintf("%1.0f",$a); // makes $a a string.
 
// Here we let the parser give the addition a try. Note that this gives INF (meaning infinity).
echo $a+$a . "<br/>";
 
// We try to add the number via the add_as_string function.
// Note that when $a==$b, every loop of the for-loop is equal to multiplication with two. Meaning that if you run the loop twice, it's the same as 4*$a, and so fourth.
for($x=0;$x<1;$x++){
	$a = add_as_string($a,$a);
}
// We output the value of the 
echo $a . "<br/>";
 
// We try putting through two number's that are unequal in length, therefore making use of the zero-padding.
$a = add_as_string("5","50");
echo $a . "<br/>";
 
// We try putting through a number and a string, which will provide an error.
$a = add_as_string(5,$a);
echo $a . "<br/>";
?>

The above code outputs:
INF
179769313486231590772930519 … 79716304835356329624224137216
55
At least one of the provided numbers was not a string!

Notes

Be aware that the script can only be used to calculate addition of integers!
It should be fairly simple to adopt the method to substraction of numbers. My next script might be multiplication of numbers larger than 2^1023. We’ll se ;D

Ricehigh Micro guides , ,

Concept unit converter

February 12th, 2009

Introduction

This is my fourth guide and is, like my prime generator, just some code I did for fun, while I was bored in front of my computer:)
So what are we going to do today? Well, we’re going to program a unit converter “Google-style”. What I wanted to do was to get a user to input a unit. For instance “4 pounds” and then the script would output how much this was in several other units. And because units like “pounds” can be addresses in many ways (like “lb”, “lbs”, “pound”, and so on) I wanted to make the script understand every single of them and use them as if the user had used the input “pounds”.

The code

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
// Concept unit converter
echo "You can use this script to convert from/to any of the most common units in mass, distance and speed<br/>Just enter, for instance: 13 km, and then the system will calculate how long 13 km is in other units.";
echo '<form action="test.php" method="get"><input type="text" name="q" size="15"/><input type="submit" value="submit"/></form>';
$input = strtolower($_GET['q']);
$number = floatval($input);
list( , $unit) = preg_split("/[\s,.1234567890]+/", $input);
$original_unit = $unit;
//Mass
$allowed["mass"] = array("kilogram" => "kg", "kilograms" => "kg", "kgs" => "kg", "grams" => "g", "gram" => "g", "lb" => "lbs", "pounds" => "lbs", "pound" => "lbs", "ounces" => "ounce", "stones" => "stone");
$conv["mass"] = array("kg" => 1, "lbs" => 2.204623, "g" => 1000, "stone" => 0.157473, "ounce" => 35.27);
 
// Distance
$allowed["distance"] = array("meter" => "m", "meters" => "m", "kilometer" => "km", "kilometers" => "km", "inch" => "in", "inches" => "in", "mile" => "mi", "miles" => "mi", "yard" => "yd", "yards" => "yd");
$conv["distance"] = array("m" => 1, "km" => 0.001, "in" => 39.37007874, "mi" => 0.0006213712, "yd" => 1.093613);
 
// Speed / velocity
$allowed["speed"] = array("kmh" => "km/h", "mps" => "m/s", "kms" => "km/s");
$conv["speed"] = array("km/h" => 1, "mph" => 0.6213712, "m/s" => 0.2777778, "km/s" => 0.0002777778);
 
$types = array("mass", "distance", "speed");
 
foreach($types as $type){
	if(array_key_exists($unit,$allowed[$type]) || array_key_exists($unit,$conv[$type])){
		if(array_key_exists($unit,$allowed[$type]))
			$unit = $allowed[$type][$unit];
		echo "<table><tr><td style=\"text-align:right;\">";
		echo "<b>" . number_format($number,2,"."," ") . "</b></td><td><b> " . $original_unit . "</b></td></tr>";
		$number = $number/$conv[$type][$unit];
		foreach($conv[$type] as $unit_conv => $conv_ratio){
			if($unit != $unit_conv)
				echo "<tr><td style=\"text-align:right;\">" . number_format($number*$conv_ratio,2,"."," ") . "</td> <td>$unit_conv</td></tr>";
		}
		echo "</table>";
	}
}

It is clear from the code that the array $allowed[] specifies what terms are allowed in the script and it’s a translation table to the correct unit (”the correct unit” is specified by you). The array $conv[] contains the conversion ratio. As you see from the code the conversion ratio is always relative to the first unit in $conv[].

Good luck converting:D

Important note: This script can only be used for units with a specific ratios between them. This means that it for instance cannot be used for converting Celsius to Fahrenheit and vice versa.

Ricehigh Micro guides , ,

How to generate primes

February 2nd, 2009

Introduction

Here’s a micro guide on how to generate prime numbers in a given interval with PHP.

A prime number is a natural number (a positive integer) which has exactly two distinct natural number divisors (1 and the number itself).

The Code

What we want to do is to create a function that takes a minimum and a maximum value of primes values we want to find. Then we try to divide the number by every number bigger than 1 and smaller than itself and determine if it has a remainder on any of the calculation. If it has on every caltulation we’ve got a prime, if not, we don’t.
I’ve made the script to only use odd numbers, because 2 is the only non-odd prime.

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
<?php
function prime_generator($from,$to,$return=false){
	if(!($from%2))
		$from++;
	if($from <= 2){
		$from = 3;
		if($return)
			$primes .= "2, ";
		else
			echo "2, ";
	}
 
	for($x=$from; $x <= $to; $x+=2){
		$prime=true;
		for($y=$x-1;$y>1;$y--){
			if(!($x%$y)){
				$prime=false;
				}
		}
		if($prime){
			if($return)
				$primes .= $x . ", ";
			else
				echo $x . ", ";
		}
	}
	if($return)
		return $primes;
}
$primes = prime_generator(0,100, true);
echo $primes;
?>

You can use the function either with or without the $return parameter set. If it’s set to true it will return all primes in the given interval, if not, it gives the output right away.

Ricehigh Micro guides , , ,