Home > Article > Backend Development > The sum of values that are multiples of N in the interval, algorithm
Example: Find the sum of values between 10-50 that are multiples of 7. There are special rewards
I often encounter some problems when learning PHP. What about daffodils, what are the sums of prime numbers, etc. Today I I saw this question on a website. The answer to this question is basically the following function.
<code>function newSumMultiple($min,$max,$multiple){ $sum = 0; for(;$min<$max;++$min){ if(!($min % $multiple)){ $sum += $min; } } return $sum; }</code>
I had a sudden thought today. It has always been like this. When the teacher taught, he always followed the instructions and I was really speechless. So I thought of the following idea.
<code>function sumMultiple($min,$max,$multiple){ $remainder=$min % $multiple; if($remainder){ $remainder = $min + $remainder + 1; $min = $remainder; }else{ $remainder = $min; } $sum = 0; while(true){ $sum += $remainder; $min += $multiple; if($min >= $max){ break; } $remainder = $remainder + $multiple; } return $sum; }</code>
Asking for a new algorithm, it is best to attach the code.
Example: Find the sum of values between 10-50 that are multiples of 7. There are special rewards
I often encounter some problems when learning PHP. What about daffodils, what are the sums of prime numbers, etc. Today I I saw this question on a website. The answer to this question is basically the following function.
<code>function newSumMultiple($min,$max,$multiple){ $sum = 0; for(;$min<$max;++$min){ if(!($min % $multiple)){ $sum += $min; } } return $sum; }</code>
I had a sudden thought today. It has always been like this. When the teacher taught, he always followed the instructions and I was really speechless. So I thought of the following idea.
<code>function sumMultiple($min,$max,$multiple){ $remainder=$min % $multiple; if($remainder){ $remainder = $min + $remainder + 1; $min = $remainder; }else{ $remainder = $min; } $sum = 0; while(true){ $sum += $remainder; $min += $multiple; if($min >= $max){ break; } $remainder = $remainder + $multiple; } return $sum; }</code>
Asking for a new algorithm, it is best to attach the code.
Use min and max to divide multiple to get the upper and lower bounds respectively, and then use the arithmetic sequence summation formula