Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.