Aliquot Sequence | C ++ implementation of Optimized approach to generate Aliquot Sequence ; Function to calculate sum of all proper divisors ; Note that this loop runs till square root of n ; If divisors are equal , take only one of them ; else Otherwise take both ; calculate sum of all proper divisors only ; Function to print Aliquot Sequence for an input n . ; Print the first term ; Calculate next term from previous term ; Print next term ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getSum ( int n ) { for ( int i = 1 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) sum = sum + i ; { sum = sum + i ; sum = sum + ( n / i ) ; } } } return sum - n ; } void printAliquot ( int n ) { printf ( " % d ▁ " , n ) ; unordered_set < int > s ; s . insert ( n ) ; int next = 0 ; while ( n > 0 ) { n = getSum ( n ) ; if ( s . find ( n ) != s . end ( ) ) { cout << " Repeats with " break ; } cout << n << " ▁ " ; s . insert ( n ) ; } } int main ( ) { printAliquot ( 12 ) ; return 0 ; }