Find all divisors of a number in c language to output all divisors (factors) of an integer excluding itself, multiple algorithm implementations

topic:

Method 1: Implementation of for loop statement

The code example is as follows:

#include <stdio.h>
int main()
{
    int num, i;
    scanf("%d", &num);
    for (i = 2; i < num; i++)
    {
        if (num % i == 0)
            printf("%d ", i);
        else
            continue;
    }
    return 0;
}

The running results are as follows: (take 99 as an example)

Method 2: Implementation of while loop statement

The code example is as follows:

#include <stdio.h>
int main(int argc, char* argv[])
{
    int i, a, sum;
    while (scanf_s("%d", &a) != EOF)
    {
        printf("%d 的约数有:", a);
        sum = 0;
        for (i = 1; i <= a; i++)
            if (a % i == 0)
                sum += i, printf("%d ,", i);
        printf(" 约数和为 %d\n", sum);
    }
    return 0;
}

The running results are as follows: (Here, 99 is taken as an example, the output includes 1 and its own two divisors, and the sum of the constraints is calculated)

Editor's note: The above-mentioned various methods of writing code for this topic are welcome to collect, learn from and forward;

               The above code is for reference only, if you have any questions, you are welcome to criticize and correct in the message area;

               All rights reserved, reprints must be investigated, any similarity is purely coincidental, please indicate the source for reprinting.

               By CRH380AJ2808 2022.04.23
————————————————

Copyright statement: This article is the original article of CSDN blogger "CRH380AJ2808", following the CC 4.0 BY-SA copyright agreement, please attach the original text for reprinting Source link and this statement.
Original link: https://blog.csdn.net/JH13thpig/article/details/124294723

Guess you like

Origin blog.csdn.net/JH13thpig/article/details/124361837