i have a question that i want to display the numbers up to 100 where the sum of their digits is 7.
can any one help me suppos there is 25 . in ths 2+5=7 then it will be displayed. i have problem to break 25 as 2 and 5
i have a question that i want to display the numbers up to 100 where the sum of their digits is 7.
can any one help me suppos there is 25 . in ths 2+5=7 then it will be displayed. i have problem to break 25 as 2 and 5
Well, there's 7, 16, 25, 34, 43, 52, 61 and 70. Now you have the answer, so you don't need a program.
There is a finite number of combinations as the answer to the question, and the list is small. For example:
7, 0 + 7 = 7
16, 1 + 6 = 7
25, 2 + 5 = 7
34, 3 + 4 = 7
43, 4 + 3 = 7
52, 5 + 2 = 7
61, 6 + 1 = 7
70, 7 + 0 = 7
If you need it to be dynamic, and work for any number below 10 (e.g. 6), start with that number and add 9 to it, each time you do so up until $num * 10
will give you the numbers you're looking for.
This C code will do it. You'll need to translate to PHP:
for (i = 7; i <= 70; i+= 9)
printf ("%d\n", i);
If you want to take an arbitrary two-digit number and sum the digits, you need an integer divide and modulo operator.
25 div 10 -> 2
25 mod 10 -> 5
Integer division of $x
by $y
can be done in PHP with $x - ($x % $y)) / $y
if both $x
and $y
are positive integers (as they are in your case). Modulo uses the %
operator such as $x % $y
.
I'm having a hard time to think why one would need such a program.
Anyways, 7 is one such number, next is 16, clearly to get the same sum you need to increment the 10's digit by one and decrement ones digit by 1. So effectively you are incrementing the number by 9:
for($i=7;$i<=70;$i+=9) {
echo $i."\n";
}
Output:
7
16
25
34
43
52
61
70
EDIT:
If you want to write this without using the modulus operator(I know, no one would do that!!), you can take each number, split it into digits using preg_split and then find the sum of digits using array_sum:
for($i=1;$i<=100;$i++) {
if(array_sum(preg_split('//',$i)) == 7)
echo $i."\n";
}