Home > Back-end >  Smith Number program never ends (infinite loop)
Smith Number program never ends (infinite loop)

Time:10-28

#include <stdio.h>

void smith(int n) {
  int num, sd = 0, sf = 0, i, t, c, j;
  num = n;
  while (num > 0) {
    sd = sd   (num % 10);  // Sum of digits of input number
    num = num / 10;
  }
  num = n;
  while (num > 1)  // To calculate factors of the number
  {
    for (i = 1; i <= num; i  ) {
      if (num % i == 0) break;
    }
    c = 0;
    t = i;
    for (j = 1; j <= i; j  )  // To check if the numbers are prime
    {
      if (i % j == 0) c  ;
    }
    if (c == 2) {
      while (i > 0) {
        sf = sf   (i % 10);
        i = i / 10;
      }
    }
    num = num / t;
  }
  if (sd == sf) {
    printf("Smith Number");
  } else
    printf("Not a Smith Number");
}

int main() {
  int n;
  printf("Enter a number");
  scanf("%d", &n);
  smith(n);
}

I was expecting the program to identify whether the input number is a Smith number or not.

Every time I try to run the code, it just doesn't give an output. It just takes an input and then probably goes into an infinite loop. Why?

CodePudding user response:

The problem is that you are introducing an infinite loop (a very elusive one). Look at these lines of code:

for (i = 1; i <= num; i  ) {
    if (num % i == 0) break;
}

You are testing if the num is divisible by 1 (which is true for every number), so it will always break, and i will be 1.

Later on, you divide num by this number until num is less than or equal to one, but dividing by one yields the same number, so the loop will never end. If the loop never ends, then your program will stall, hence the program never printing a result.

The solution is simple: start your factoring loop at 2, not 1. Like this:

for (i = 2; i <= num; i  ) {
    if (num % i == 0) break;
}

1 is a factor of every number, so it is not a useful factor.

CodePudding user response:

Because the value of t is always 1, num is always stay the same, while loop endlessly. You can fix it like this:

for (i = 2; i <= num; i  ) {
  if (num % i == 0) break;
}
  •  Tags:  
  • c
  • Related