Sum of all divisors from 1 to n | C ++ program to find sum of all divisor of number up to ' n ' ; Utility function to find sum of all divisor of number up to ' n ' ; Find all divisors of i and add them ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int divisorSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { for ( int j = 1 ; j * j <= i ; ++ j ) { if ( i % j == 0 ) { if ( i / j == j ) sum += j ; else sum += j + i / j ; } } } return sum ; } int main ( ) { int n = 4 ; cout << " ▁ " << divisorSum ( n ) << endl ; n = 5 ; cout << " ▁ " << divisorSum ( n ) ; return 0 ; }