Aliquot Sequence | Java 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 code
import java . util . * ; class GFG { static int getSum ( int n ) { for ( int i = 1 ; i <= Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) { sum = sum + i ; } { sum = sum + i ; sum = sum + ( n / i ) ; } } } return sum - n ; } static void printAliquot ( int n ) { System . out . printf ( " % d ▁ " , n ) ; TreeSet < Integer > s = new TreeSet < > ( ) ; s . add ( n ) ; int next = 0 ; while ( n > 0 ) { n = getSum ( n ) ; if ( s . contains ( n ) && n != s . last ( ) ) { System . out . print ( " Repeats with " + n); break ; } System . out . print ( n + " ▁ " ) ; s . add ( n ) ; } } public static void main ( String [ ] args ) { printAliquot ( 12 ) ; } }