Adding fractions by n denominator in for_loop (PHP) - php

I'm trying to make it so it loops fractions as 1, 1/2, 1/3, 1/4, etc up to 1/100, then add all them together and only show the sum and not the chain of fractions.
The code I have so far looks like this:
<?
$sum = 0;
for($n = 1; $n<=1/100; $n+=1/$n)
{
$sum = $sum + $n;
}
echo $sum;
But it never gives me the right answer, which is 5.18. Any advice?

You need to limit the loop. And you need to increment $n
$sum = 0;
for($n = 1; $n<=100; $n++)
{
$sum = $sum + (1/$n);
}
echo $sum;
//answer 5.1873775176396

Just FYI, for a simple operation like this, your for loop does not even need a body.
$sum = 0;
for($n=1; $n<=100; $sum +=(1/$n++));
echo $sum;
See example four in the php for documentation.

for($n = 1; $n<=; $n+=1/$n)
You must define a limit insecond parameter of for, it runs in infinity
EDIT:
Between second and third parameter, you must insert ;

<?php
$sum = 0;
for ($n=1; $n<=100; $n++) {
$sum = $sum + (1/$n);
}
echo $sum;
// or use round if you want it rounded
//echo round($sum,2);
This code is PSR-2 compliant

Try this:
for ($n = 0, $sum = 0; $n < 100; $n++, $sum += 1 / $n);
echo $sum;

Related

PHP calculating two arrays and then add their sum

I want to calculate an array to another array and then add both like this :
Array1(4,8,7,12);
Array2(3,6);
the result is like this :
3x4+3x8+3x7+3x12+6x4+6x8+6x7+6x12 = 279
I tried with this code and since I'm still new with php I still didn't make any tips I'll be glad thanks in advance
<?php
tab1(4,8,7,12);
tab2(3,6);
$s=0;
for($i=0; $i<$tab1[3]; $i++){
for($j=0; $j<$tab2[1]; $j++){
$s = $s + tab[i] * tab[j];
}
echo "$s";
}
?>
This is actually a piece of cake. I am not sure what tab1 means but I assume you are trying to use this function to get an array of desired(input) numbers.
Using a foreach loop to loop over the two arrays, I came up with the code below:
<?php
$a = [4,8,7,12];
$b = [3,6];
$sum = 0;
foreach ($b as $valueInB) {
foreach ($a as $valueInA) {
$sum += $valueInA * $valueInB;
}
}
echo $sum;
?>
which results in:
279
if you are insisting on using a for loop you can run the code below to get the same result:
<?php
$a = [4,8,7,12];
$b = [3,6];
$sum = 0;
$bLength = count($b);
$aLength = count($a);
for ($i=0; $i < $bLength ; $i++) {
$valueInB = $b[$i];
for ($j=0; $j < $aLength ; $j++) {
$valueInA = $a[$j];
$sum += $valueInA * $valueInB;
}
}
echo $sum;
?>
Please note that you should use the count outside of the loop because looping over the array and calling count each time is not an efficient way. (Thanks to Will B for the comment)
For a more simplistic approach without iteration you can use array_sum on the two arrays.
Example: https://3v4l.org/3gtgE
$a = [4,8,7,12];
$b = [3,6];
$c = array_sum($a) * array_sum($b);
var_dump($c);
Result
int(279)
This works because of the order of operations of:
(3*4) + (3*8) + (3*7) + (3*12) + (6*4) + (6*8) + (6*7) + (6*12) = 279
Equates to the same as the sum of a multiplied by the sum of b:
(4+8+7+12) * (3+6) = 279

PHP Add numbers 1-10 and only even numbers 1-10. Display sums separately with one loop

I'm trying to use ONE PHP for loop to echo the sum of the numbers 1-10 as well as echo the sum of only the even numbers. I seem to have a problem as these iterations won't be "parallel"
Code:
<?php
$sum = 0; $evensum = 0;
for($x = 1, $y=2; $x<=10, $y<=6; $x++, $y += 2) {
$sum = $sum + $x; $evensum = $evensum + $y;
}
echo "total sum= ". $sum, ", even sum=" . $evensum;
?>
total sum should reflect 55 (1+2+3+4+5+6+7+8+9+10) and even sum should reflect 30 (2+4+6+8+10)
Just Use
<?php
$sum = 0; $evensum = 0;
for($x = 1; $x<=10; $x++) {
// sum all the number
$sum = $sum + $x;
// check the number is even
if( $x % 2 === 0 ) {
// sum only the even numbers
$evensum = $evensum + $x;
}
}
// output
echo "total sum= ". $sum, ", even sum=" . $evensum;
?>
Another approach is using range() and array_functions
$arr=range(1,10);
echo $sum=array_sum($arr);
function even($var)
{
return(!($var & 1));
}
echo $even=array_sum(array_filter($arr, "even"));
Sum all ranges
$all_sum=array_sum(range(1,10));
Sum even number (0,2,4,6,8,10)
$even_sum = array_sum(range(0,10,2));

Having issue using for loop and array together

PHP: Here is what I am supposed to accomplish. And below is my code. I am definitely missing something..
Write a FOR loop using an array that prints “The product of first 10 numbers is ” followed by the product of numbers 1 through 10. Here’s a hint: do NOT begin counter at 0 or else the product will be a zero!
<?php
$numbers = 0;
$numbers = range(1 , 10);
$arrlength = count($numbers);
for ($x = 1; $x <= $arrlength; $x++) {
$numbers[$x] = $numbers + $x;
}
echo "The product of first 10 numbers is $numbers.<br>";
?>
Essentially what you're doing is creating a factorial function for a limited case. The problems with your implementation are that you seemed to re-use the $numbers variable when it should be one variable to hold the product and one for the array 1-10. The second issue is in your loop where you loop from 1-10 but what you probably really want to do is loop from 0-9 which are the array indices so that you can get the values from the array like this:
<?php
$prod = 1;
$numbers = range(1 , 10);
$arrlength = count($numbers);
for ($x = 0; $x < $arrlength; $x++) {
$prod *= $numbers[$x];
}
echo "The product of first 10 numbers is $prod.<br>";
?>
The output of which will be:
The product of first 10 numbers is 3628800.
Please note I have not tested this code, but I'm sure it should work.
<?php
$numbers = range(1, 10);
$product = 1;
for ($i = 0; $i < count($numbers); $i++) {
$product *= $numbers[$i];
}
echo 'The product of the first 10 numbers is ' . $product . '<br />';
?>

Decoding function to better understand

I am revisiting PHP and want to relearn where i lack and i found one problem, i am unable to understand the following code, where as it should output 6 according to the quiz, i got it from but i broke it down to simple pieces and commented out to better understand, according to me the value of $sum should be 4, but what i am doing wrong, maybe my breakdown is wrong?
$numbers = array(1,2,3,4);
$total = count($numbers);
//$total = 4
$sum = 0;
$output = "";
$i = 0;
foreach($numbers as $number) {
$i = $i + 1;
//0+1 = 1
//0+2 = 2
//0+3 = 3
//0+4 = 4
if ($i < $total) {
$sum = $sum + $number;
//1st time loop = 0 < 4 false
//2nd time loop = 0 < 1 false
//3rd time loop = 0 < 2 false
//5th time loop = 0 < 3 false
//6th time loop = 4 = 4 true
//$sum + $number
//0 + 4
//4
}
}
echo $sum;
This is very basic question and might get down vote but it is also a strong backbone for people who want to become PHP developer.
You don't understand the last part in the loop. It actually goes like this now:
if($i < $total) {
$sum = $sum + $number;
//1st time loop: $sum is 0. $sum + 1 = 1. $sum is now 1.
//2nd time loop: $sum is 1. $sum + 2 = 3. $sum is now 3.
//3rd time loop: $sum is 3. $sum + 3 = 6. $sum is now 6.
//4th time loop: it doesn't get here. $i (4) < $total (4)
//This is false, so it doesn't execute this block.
}
echo $sum; // Output: 6
I altered your script a little so that it will print out what it's doing as it goes. I find it useful to do this kind of thing if I'm having a hard time thinking through a problem.
$numbers = array(1,2,3,4);
$total = count($numbers);
$sum = 0;
$i = 0;
$j = 0;
foreach($numbers as $number) {
$i = $i + 1;
echo "Iteration $j: \$i +1 is $i, \$sum is $sum, \$number is $number";
if ($i < $total) {
$sum = $sum + $number;
echo ", \$i is less than \$total ($total), so \$sum + \$number is: $sum";
} else {
echo ", \$i is not less than \$total ($total), so \$sum will not be increased.";
}
echo '<br>'; // or a new line if it's CLI
$j++;
}
echo $sum;
Lets Explain
Your initial value of $i is 0 but when you start looping you increment it by 1, so the start value of $i is 1.
When checking the condition you did't use equal sign to check for the last value whether you start value is 1. So its clear that your loop must be run for 1 less of total.
$i = 0;
foreach($numbers as $number) {
$i += 1;
if ($i < $total)
$sum += $number;
}
echo $sum;
Analysis
Step: 1 / 4
The value of $number is: 1 And The value of $i is: 1
Step: 2 / 4
The value of $number is: 2 And The value of $i is: 2
Step: 3 / 4
The value of $number is: 3 And The value of $i is: 3
When the loop again go for a check the value of $i increased by 1 and at 4. So trying to match the condition if ($i < $total), where the value of $i and $total is equal, so it will return false. So the loop only run for 3 time.
Result
6

Get the sum of all digits in a numeric string

How do I find the sum of all the digits in a number in PHP?
array_sum(str_split($number));
This assumes the number is positive (or, more accurately, that the conversion of $number into a string generates only digits).
Artefactos method is obviously unbeatable, but here an version how one could do it "manually":
$number = 1234567890;
$sum = 0;
do {
$sum += $number % 10;
}
while ($number = (int) ($number / 10));
This is actually faster than Artefactos method (at least for 1234567890), because it saves two function calls.
Another way, not so fast, not single line simple
<?php
$n = 123;
$nstr = $n . "";
$sum = 0;
for ($i = 0; $i < strlen($nstr); ++$i)
{
$sum += $nstr[$i];
}
echo $sum;
?>
It also assumes the number is positive.
function addDigits($num) {
if ($num % 9 == 0 && $num > 0) {
return 9;
} else {
return $num % 9;
}
}
only O(n)
at LeetCode submit result:
Runtime: 4 ms, faster than 92.86% of PHP online submissions for Add Digits.
Memory Usage: 14.3 MB, less than 100.00% of PHP online submissions for Add Digits.
<?php
// PHP program to calculate the sum of digits
function sum($num) {
$sum = 0;
for ($i = 0; $i < strlen($num); $i++){
$sum += $num[$i];
}
return $sum;
}
// Driver Code
$num = "925";
echo sum($num);
?>
Result will be 9+2+5 = 16
Try the following code:
<?php
$num = 525;
$sum = 0;
while ($num > 0)
{
$sum= $sum + ($num % 10);
$num= $num / 10;
}
echo "Summation=" . $sum;
?>
If interested with regex:
array_sum(preg_split("//", $number));
<?php
echo"----Sum of digit using php----";
echo"<br/ >";
$num=98765;
$sum=0;
$rem=0;
for($i=0;$i<=$num;$i++)
{
$rem=$num%10;
$sum=$sum+$rem;
$num=$num/10;
}
echo "The sum of digit 98765 is ".$sum;
?>
-----------------Output-------------
----Sum of digit using php----
The sum of digit 98765 is 35
// math before code
// base of digit sums is 9
// the product of all numbers multiplied by 9 equals 9 as digit sum
$nr = 58821.5712; // any number
// Initiallization
$d = array();
$d = explode(".",$nr); // cut decimal digits
$fl = strlen($d[1]); // count decimal digits
$pow = pow(10 ,$fl); // power up for integer
$nr = $nr * $pow; // make float become integer
// The Code
$ds = $nr % 9; // modulo of 9
if($ds == 0) $ds=9; // cancel out zeros
echo $ds;
Assume you want to find the sum of the digits of a number say 2395 the simplest solution would be to first split the digits and find out the sum then concatenate all the numbers into one single number.
<?php
$number=2;
$number1=3;
$number2=9;
$number3=5;
$combine=$number.$number1.$number2.$number3;
$sum=$number+$number1+$number2+$number3;
echo "The sum of $combine is $sum";
?>
One way of getting sum of digit however this is a slowest route.
$n=123;
while(($n=$n-9)>9);
echo "n: $n";
<html>
<head>
<title>detail</title>
</head>
<body>
<?php
$n = 123;
$sum=0; $n1=0;
for ($i =0; $i<=strlen($n);$i++)
{
$n1=$n%10;
$sum += $n1;
$n=$n/10;
}
echo $sum;
?>
</body>
</html>
Here's the code.. Please try this
<?php
$d=0;
$num=12345;
$temp=$num;
$sum=0;
while($temp>1)
{
$temp=$temp/10;
$d++;
}
echo "Digits Are : $d </br>";
for (;$num>1;)
{
$d=$num%10;
$num=$num/10;
$sum=$sum+$d;
}
echo "Sum of Digits is : $sum";
?>

Categories