Jump to content

Basic PHP needs new eyes to find problem


JacksonSoccerBoy

Recommended Posts

Im trying to create a website that will find the sum of all integers up to the number entered (ex. 5 would be 1+2+3+4+5= 15)

 

I cant get this to work It has to be something simple Im over looking

Thanks in advance  ;D

 

<code>

 

<?php

 

$num = $_GET["loop"];

$first = 0;

$answer = 0;

 

while ($num <= $first)

{

 

$first++;

$answer == $first + $answer;

PRINT $first;

 

 

 

PRINT "The sum of the numbers from 1 through $num is ";

PRINT $answer;

 

?>

 

 

</code>

That's inefficient, use Faulhaber's formula.

 

$num = 101;
echo ($num * ($num + 1) / 2);

 

Edit: fitting it into your script...

 

<?php
$num = $_GET['loop'];
$sum = $num * ($num + 1) / 2;

echo "The sum of the numbers from 1 through $num is $sum";
?>

That's inefficient, use Faulhaber's formula.

 

$num = 101;
echo ($num * ($num + 1) / 2);

 

Edit: fitting it into your script...

 

<?php
$num = $_GET[lloopl];
$sum = $num * ($num + 1) / 2;

echo "The sum of the numbers from 1 through $num is $sum";
?>

 

THANKS and to think I spent an hour troubleshooting what was wrong with my code when simple math would have done the trick

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.