Sum of all divisors from 1 to N | Set 2 | Java program for the above approach ; Functions returns sum of numbers from 1 to n ; Functions returns sum of numbers from a + 1 to b ; Function returns total sum of divisors ; Stores total sum ; Finding numbers and its occurence ; Sum of product of each number and its occurence ; Driver code
class GFG { static final int mod = 1000000007 ; public static int linearSum ( int n ) { return ( n * ( n + 1 ) / 2 ) % mod ; } public static int rangeSum ( int b , int a ) { return ( linearSum ( b ) - linearSum ( a ) ) % mod ; } public static int totalSum ( int n ) { int result = 0 ; int i = 1 ; while ( true ) { result += rangeSum ( n / i , n / ( i + 1 ) ) * ( i % mod ) % mod ; result %= mod ; if ( i == n ) break ; i = n / ( n / ( i + 1 ) ) ; } return result ; } public static void main ( String [ ] args ) { int N = 4 ; System . out . println ( totalSum ( N ) ) ; N = 12 ; System . out . println ( totalSum ( N ) ) ; } }