7-45 find completion (20 points)

Posted by SN1P3R_85 on Thu, 13 Feb 2020 20:17:20 +0100

The so-called completion is that the number is exactly equal to the sum of the factors except oneself. For example: 6 = 1 + 2 + 3, where 1, 2 and 3 are factors of 6. This problem requires programming to find all the completions between any two positive integers m and n.

Input format:

Input two positive integers m and n (1 < m ≤ n ≤ 10000) in a row, separated by spaces.

Output format:

Output the factorization in the form of factor accumulation of each completion in a given range line by line. Each completion takes up one line. The format is "completion = factor 1 + factor 2 +... + factor k", where the completion and factor are given in increasing order. If there is no completion in the interval, "None" is output.

Input example:

2 30

Output example:

6 = 1 + 2 + 3
28 = 1 + 2 + 4 + 7 + 14

 

 1 #include <stdio.h>
 2 
 3 int isPerfect(int num);
 4 void output(int num);
 5 
 6 int main(int argc, char const *argv[])
 7 {
 8     int m, n;
 9     int i;
10     int count = 0;
11 
12     scanf("%d %d", &m, &n);
13 
14     for ( i = m; i <= n; i++ ) {
15         int num = i;
16         if ( isPerfect( num ) ) {
17             count++;
18             output(num);
19         }
20     }
21     if ( count == 0 ) {
22         printf("None\n");
23     }
24     return 0;
25 }
26 
27 int isPerfect(int num)
28 {
29     int nSum = 0;
30     int ret = 0;
31     for ( int i = 1; i < num; i++ ) {
32         if ( num % i == 0 ) {
33             nSum += i;
34         }
35         // To judge whether a number is complete, we need to add up all its factors
36         if ( nSum == num && i + 1 == num) {
37             ret = 1;
38         }
39     }
40     return ret;
41 }
42 
43 void output(int num)
44 {
45     int nSum = 0;
46     printf("%d = ", num);
47     for ( int i = 1; i < num; i++ ) {
48         if ( num % i == 0 ) {
49             nSum += i;
50             printf("%d", i);
51             if ( nSum == num ) {
52                 break;
53             } else {
54                 printf(" + ");
55             }
56         }
57     }
58     printf("\n");
59 }

Topics: C Programming