1

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

ScottMcGready
  • 1,612
  • 2
  • 24
  • 33
Rajanikant
  • 11
  • 1
  • 2

5 Answers5

3

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";
}
codaddict
  • 445,704
  • 82
  • 492
  • 529
1

This code will do it. It uses mathematical knowledge that the first and last numbers that satisfy the condition are, respectively, 7 and 70. It also knows that the next number in sequence is always nine more than the last:

for ($num = 7; $num <= 70; $num += 9)
    echo $num . "\n";

If you want to take an arbitrary two-digit number and sum the digits, you need an integer divide and modulo operator, such as:

25 div 10 -> 2
25 mod 10 -> 5

Integer division of $x by $y can be done in PHP with casting, while modulo uses the % operator.

A program giving the more adaptable case is shown below:

for ($num = 1; $num < 100; $num++) {
    $tens = (int)($num / 10);
    $ones = $num % 10;
    if ($tens + $ones == 7)
        echo $num . "\n";
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

well you could always use the following code to generate numbers up to any limit

all variables are integers

for(i=1;i<=n;i++){
    //where n is the upper limit.In this case it is 100
    n=i;

    while(n!=0){

        d=n%10;// to extract the last digit

        s=s+7;//  to calculate sum of digits

        n=n/10;// to remove the last digit

    }

    if(s==7)

    System.out.println(+i);

}//close for loop
Andy Holmes
  • 7,817
  • 10
  • 50
  • 83
0

Well, there's 7, 16, 25, 34, 43, 52, 61 and 70. Now you have the answer, so you don't need a program.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
0

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.

Andy E
  • 338,112
  • 86
  • 474
  • 445