A program which finds the divisors of the numbers

This is the decision given in the book but for some reason it doesn't work at all when i type in odd numbers like 3, 5, 7, 9, 11, 13 etc. Also i can't understand what i < (num / 2) + 1; does. For comparison below is the code which i wrote:

1
2
3
4
5
6
7
8
9
10
11
  #include <stdio.h>
int main(void)
{
	int num, i;
	printf("Enter the number to test: ");
	scanf_s("%d", &num);
	for (i = 2; i < (num / 2) + 1; i = i + 1)
		if ((num % i) == 0)
			printf("%d ", i);
	return 0;
}

_______________________________________________
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main(void)
{
	int num, i;
		printf ("Type in a number: ");
		scanf_s ("%d", &num);
		for (i = 1; i <= num; i = i + 1)
			if ((num % i) == 0)
				printf ("%d is this number's divisor ", i);
		return 0;
}
3, 5, 7, 9, 11, 13
Most of those are prime numbers. Apart from 9 which is 3 * 3.


i < (num / 2) + 1 this is just a way of cutting out unnecessary iterations. Say the number is 100, its largest factor is 50, there's no point continuing to test whether 51 or 52 or 53 etc. are factors.
i < (num / 2) + 1 this is just a way of cutting out unnecessary iterations. Say the number is 100, its largest factor is 50, there's no point continuing to test whether 51 or 52 or 53 etc. are factors

OK. But what does + 1 do? Would you give me an example with a number how the program proceeds. Also 100 is 100's divisor too but on this way the program will never find it out.
But what does + 1 do?

If we go back to this line:
for (i = 2; i < (num / 2) + 1; i = i + 1)
what is it saying?

It says variable i starts from 2. It is increased by 1 at the end of each iteration.
for (i = 2; ........; i = i + 1)
What does the part in the middle do? It is a condition. The condition is tested, if it is true, the body of the loop is executed.

Let's say that num is 100. (num/2) will be 50. If the condition is i < (num / 2) that is saying, the same as i < 50

The result would be the loop is executed for all values of i from 2 to 49 inclusive.

If we add 1, the condition becomes i < 51 , now the loop is executed for values from 2 to 50. It includes 50, rather than stopping at 49.

Personally I'd have used a <= operator instead, i <= (num / 2)

Also 100 is 100's divisor too but on this way the program will never find it out.

That is true. But the same applies to 1, which is also ignored. Partly it comes down to interpretation of the question. But either way, going through twice as many calculations just to arrive at something which is already a certainty would be a poor design. We know already that none of the values 51 to 99 will be factors. We also know that 100 will be a factor. There's no need to do multiple iterations to determine something which we already knew in the first place.
Last edited on
Thank you very much for the good explanation. This helped me a lot.
Topic archived. No new replies allowed.