본문 바로가기

Eng Ver

[C][Algorithm]The logic to get the divisors and the codes in C


 - Here we go


Let's get the divisors of n!


1) Basic - Divide n in i ( i substitutes from 1 to n). If the remainder is 0, the i would be a divisor. 



1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
 
int main(void)
{
    int i,n;
    scanf("%d", &n); 
 
      for(i=1; i<=n; i++)
    {
        if((n%i)==0) 
            printf("%d\n",i); 
    }
}


2) Avoid repetition - Suppose n is 20.

1    20

2    10

4    5

5    4     ☜ It's repeated from here.

10    2

20    1

√n is the boundary to be able to avoid repetition.


1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <stdio.h>
 
int main(void)
{    
    int input,m,a,b;
    scanf("%d", &input);
 
    for(m=1;m*m<input;m++)
    {
        if(input % m == 0)
            printf("%d, %d, ",m,input/m); 
    }
    if(m*m == input)
        printf("%d, ", m);
}

You can get the number of the divisors with this logic above.


Happy coding~!!