Sparingga Sparingga - 8 days ago 7
PHP Question

How to print negation output?

function count_digit($number) {
return strlen($number);
}

for($a=1; $a<=5000; $a++){ //loop
$i=$a;
$i= (string)$i ;

$num=$a;
$number_of_digits = count_digit($num);
if ($number_of_digits == 1){

$total = $a+$i[0];

}
elseif ($number_of_digits == 2){

$total = $a+$i[0]+$i[1];


}

elseif ($number_of_digits == 3){

$total = $a+$i[0]+$i[1]+$i[2];

}

elseif ($number_of_digits == 4){

$total = $a+$i[0]+$i[1]+$i[2]+$i[3];

}


echo $total. '<br>';
}


output a : 1 2 3 4 5 6 7 8 ... 5000

output total : 2
4
6
8
10
12
14
16
18
11
13
15
17
19
21
23
25
27
29
22
24
26
28
30
32
34
36
38
40
33
35
37
39
41
43
45
47
49
51
44
46
48
50

how to make negation output total: 1 3 5 7 9 20 31 42 53

Answer

Ok, now when I understand what you are asking, lets take this approach.

You have all numbers that are not self numbers, so we will take them to array, as well as all numbers 0-5000 to compare them.

All numbers that are in all_numbers array but not in not_self_numbers array must be self numbers.

<?php
$not_self_numbers = array();
$all_numbers = array();

for($a=1; $a<=5000; $a++){ //loop
    $i=$a;
    $i= (string)$i ;
    $all_numbers[] = $a;

    $num=$a;
    $number_of_digits = strlen($num);
    if ($number_of_digits == 1){

        $total = $a+$i[0];
        $not_self_numbers[] = $total;

    }
    elseif ($number_of_digits == 2){

        $total = $a+$i[0]+$i[1];
        $not_self_numbers[] = $total;


    }

        elseif ($number_of_digits == 3){

        $total = $a+$i[0]+$i[1]+$i[2];
        $not_self_numbers[] = $total;

    }

        elseif ($number_of_digits == 4){

        $total = $a+$i[0]+$i[1]+$i[2]+$i[3];
        $not_self_numbers[] = $total;

    }


}
$self_numbers = array_diff($all_numbers, $not_self_numbers);

foreach($self_numbers as $number) {
    echo $number."<br>";
}