How to display smallest and biggest divisor?

I have to make a program that displays all the proper divisors of a number(given by the user),basically all except the number itself and 1. If it doesn’t have any print that it’s prime.All good,done that.

There is one more thing I need to do though in case it does have proper divisors and that is to display the smallest and biggest divisor which I can’t figure out how to do ,I tried to do it as if the printed divisors were just one number ignoring the "\n" and using "number % 10" to find the last number and the while loop to find the first number,but that won’t work in case let’s say the given number is 33 and the biggest divisor is 11.

I’ll provide the code for better understanding since my question is kinda fuzzy. Everything is how I want it to be except I don’t know how to display the smallest divisor and the biggest divisor.

#include <stdio.h>

int main() {
  int n, divisor, smallest, biggest, count = 0;

  scanf("%d", &n);

  for (divisor = 2; divisor < n; divisor++) {
    if (n % divisor == 0) {
      printf("%d is divisor of %d\n", divisor, n);
    }
  }

  for (divisor = 1; divisor <= n; divisor++) {
    if (n % divisor == 0) {
      count++;
    }
  }
  if (count == 2) {
    printf("The number does not have proper divisors(it is prime)");
  }

  return 0;
}

>Solution :

I would modify your code as follows:

#include <stdio.h>

int main()
{
int n,divisor,smallest,biggest,count=0;
scanf("%d",&n);

for(divisor = 2;divisor < n;divisor++)
{
    if(n % divisor == 0)
    {
        count++;
        if (count == 1) smallest = divisor;
        biggest = divisor;
        printf("%d is divisor of %d\n",divisor,n);
    }
}

if (count == 0) printf("The number does not have proper divisors(it is prime)");
else printf("%d and %d are the smallest and biggest divisors respectively", smallest, biggest);

return 0;
}

Instead of using two for loops, I merged them into one since they’re doing the same thing. Every positive number will be divisible by 1 and itself so it’s redundant to use the second for loop. When count is 1, I know that I have found the first divisor so I set smallest equal to that. Also,everytime I find a divisor, I set biggest equal to that so that in the end, biggest is set to the last divisor found (note that you should not use an else clause here, since that will cause the program to not work when the smallest and biggest divisors are equal). I also increment count by 1 everytime a divisor is found in order to check whether the number is prime without modifying your approach too much (there are efficient ways to check for prime numbers, and I encourage you to take a look at them). And finally, I print the smallest and biggest divisors only if they exist, else I print that it is prime.

Leave a Reply