...

View Full Version : Help with a simple mathematics script



tokio
05-08-2009, 10:17 PM
I want to find the summation of the integers from 1-100. So i want to find 1+2+3+4+5+...n. The first thing i thought about issuing a for loop to print the number of terms, and i was then thinking of a function to sum up all of the terms.



for ($i=1; $i<100;$i++) {
print $i; // prints terms 1-100
}


Any recommendations to find the summation of the terms? Thanks.

Tokio

Auax
05-08-2009, 10:40 PM
for ($i=1; $i<100;$i++) {
$sum = $i;
}

echo $sum;


I think that should do it.

Len Whistler
05-08-2009, 10:47 PM
This will output the results line by line. An echo outside the loop would be the final total.


<?php
$array = range(1,100);

foreach ($array as $value) {
$sum = $sum + $value;
echo "$sum<br>";
}
?>


---------

XtremeGamer99
09-29-2009, 08:17 AM
Alternatively, you can use the arithmetic sequence equation:
(n/2)*(2a+(n-1)), where n = max number, a = min number.


<?php

$a = 1;
$n = 100;

$sum = ($n/2)*(2*($a)+($n-1));

echo sum; // echos '5050'

?>

EDIT: woah, didn't realize this topic was old. Was using the search function. <_<



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum