Home > Backend Development > C++ > body text

Number of engagements in C program?

WBOY
Release: 2023-09-02 15:41:08
forward
809 people have browsed it

Number of engagements in C program?

Here we will see the engagement number. This is a pair of numbers in which the sum of the true factors of one number is 1 more than that of the other number. We have to find these pairs

For example, this pair is like (48, 75). So the divisors of 48 are {1, 2, 3, 4, 6, 8, 12, 16, 24}, and the sum is 76. Likewise, the divisors of 75 are {1, 3, 5, 15, 25}, so the sum is 49.

Algorithm

Engaged Pairs (n) -

begin
   for num in range 1 to n, do
      sum := 1
      for i in range 2 to num, do
         if num is divisible by i, then
            sum := sum + i
            if i * i is not same as num, then
               sum := sum + num / i
            end if
         end if
         if sum > num, then
            num2 := sum – 1
            sum2 := 1
            for j in range 2 to num2, do
               if num2 is divisible by j, then
                  sum2 := sum2 + j
                  if j * j is not same as num2, then
                     sum2 := sum2 + num2 / j
                  end if
               end if
            done
            if sum2 = num + 1, then
               print the pair num and num2
            end if
         end if
      done
   done
end
Copy after login

Example

#include <iostream>
using namespace std;
void BetrothedPairs(int n) {
   for (int num = 1; num < n; num++) {
      int sum = 1;
      for (int i = 2; i * i <= num; i++) { //go through each number to get proper divisor
         if (num % i == 0) {
            sum += i;
            if (i * i != num) //avoid to include same divisor twice
            sum += num / i;
         }
      }
      if (sum > num) {
         int num2 = sum - 1;
         int sum2 = 1;
         for (int j = 2; j * j <= num2; j++){
            if (num2 % j == 0) {
               sum2 += j;
               if (j * j != num2)
               sum2 += num2 / j;
            }
         }
         if (sum2 == num+1)
         cout << "(" << num << ", " << num2 <<")" << endl;
      }
   }
}
int main() {
   int n = 5000;
   BetrothedPairs(n);
}
Copy after login

Output

1
Copy after login

The above is the detailed content of Number of engagements in C program?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template