Aliquot Sequence - GeeksforGeeks
Given a number n, the task is to print its Aliquot Sequence. Aliquot Sequence of a number starts with itself, remaining terms of the sequence are sum of proper divisors of immediate previous term. For example, Aliquot Sequence for 10 is 10, 8, 7, 1, 0. The sequence may repeat. For example, for 6, we have an infinite sequence of all 6s. In such cases we print the repeating number and stop.
Read full article from Aliquot Sequence - GeeksforGeeks
Given a number n, the task is to print its Aliquot Sequence. Aliquot Sequence of a number starts with itself, remaining terms of the sequence are sum of proper divisors of immediate previous term. For example, Aliquot Sequence for 10 is 10, 8, 7, 1, 0. The sequence may repeat. For example, for 6, we have an infinite sequence of all 6s. In such cases we print the repeating number and stop.
The solution mainly lies in the calculation of sum of all the proper divisors of the previous term.
- If we observe carefully, the divisors of the number n are present in pairs. For example if n = 100, then all the pairs of divisors are: (1,100), (2,50), (4,25), (5,20), (10,10)
- Using this fact efficiently compute divisors. While checking divisors we will have to be careful if there are two equal divisors as in case of (10, 10).
- In such case we will take only one of them in calculation of sum. This sum will contain sum of all the possible divisors so we have to subtract the number n from the sum of all divisors to get the sum of proper divisors.
We can generate the sequence by first printing the number n and then calculating the next terms using sum of proper divisors. When we compute next term, we check if we have already seen this term or not. If the term appears again, we have repeating sequence. We print the same and break the loop.
int getSum(int n){ int sum = 0; // 1 is a proper divisor // Note that this loop runs till square root // of n for (int i=1; i<=sqrt(n); i++) { if (n%i==0) { // If divisors are equal, take only one // of them if (n/i == i) sum = sum + i; else // Otherwise take both { sum = sum + i; sum = sum + (n / i); } } } // calculate sum of all proper divisors only return sum - n;}// Function to print Aliquot Sequence for an input n.void printAliquot(int n){ // Print the first term printf("%d ", n); unordered_set<int> s; s.insert(n); int next = 0; while (n > 0) { // Calculate next term from previous term n = getSum(n); if (s.find(n) != s.end()) { cout << "\nRepeats with " << n; break; } // Print next term cout << n << " "; s.insert(n); }}