Reputation: 21
ok so for my problem a magical number is defined as the following: if its every digit is larger than the sum of the digits which are on the right side of that digit. for example 94210 9 is > 4+2+1+0 4 is >2+1+0 etc ... i cant see the issue with my code but I don't get the correct output
#include <stdio.h>
void Magic_number(int left, int right, int digit) {
int remainder;
for (; left < right; left++) {
int flag = 1; int sum = 0; int y = left;
remainder = y % 10; y = y / 10;
sum += remainder;
while (y != 0 && flag)
{
if (remainder == digit)
flag = 0;
if (remainder < sum)
flag = 0;
y = y / 10;
remainder = y % 10;
sum += remainder;
}
if (y == 0 && flag) {
printf("%d ", left);
}
}
}
int main() {
int l, r, d;
printf("please enter the right bound \n");
scanf_s("%d", &r);
printf("please enter the left bound \n");
scanf_s("%d", &l);
while (l>r)
{
printf("please enter the left bound that is less than the right bound \n");
scanf_s("%d", &l);
}
printf("please enter the arbitrary digit\n");
scanf_s("%d", &d);
printf("the Magic numbers from left bound%d and the right bound %d while exluding %d\n", l, r, d);
Magic_number(l, r, d);
}
expected output
magic number in rande left=740 right 850 with excluding digit m=2
740 741 750 751 760 810 830 831 840 841 843 850
the output I get
740 750 760 770 780 790 800 810 820 830 840
Upvotes: 0
Views: 87
Reputation: 44274
There are a number of bugs in your code. One example is inside the loop where you do y = y / 10;
before calculating the remainder. Since you already divide by 10 before the loop, you actually skip a digit. Further there are some places where you do <
instead of <=
Try like:
void Magic_number(int left, int right, int digit)
{
int remainder;
for (; left <= right; left++) {
int flag = 1; int sum = 0; int y = left;
remainder = y % 10; // Get first digit
y = y / 10; // Update y
sum += remainder; // Update sum
if (remainder == digit) // Check if first digit must be skipped
flag = 0;
while (y != 0 && flag)
{
remainder = y % 10; // Get next digit
y = y / 10; // Update y
if (remainder == digit) // Check if current digit must be skipped
flag = 0;
if (remainder <= sum) // Check if current digit is higher than current sum
flag = 0;
sum += remainder; // Update sum
}
if (y == 0 && flag) {
printf("%d ", left);
}
}
}
Upvotes: 2