// Simple C++ program to
// find sum of all divisors
// of a natural number
#include<bits/stdc++.h>
using namespace std;
// Function to calculate sum of all
//divisors of a given number
int divSum(int n)
{
if(n == 1)
return 1;
// Sum of divisors
int result = 0;
// find all divisors which divides 'num'
for (int i = 2; i <= sqrt(n); i++)
{
// if 'i' is divisor of 'n'
if (n % i == 0)
{
// if both divisors are same
// then add it once else add
// both
if (i == (n / i))
result += i;
else
result += (i + n/i);
}
}
// Add 1 and n to result as above loop
// considers proper divisors greater
// than 1.
return (result + n + 1);
}
// Driver program to run the case
int main()
{
int n = 30;
cout << divSum(n);
return 0;
}
Code Example |
---|
Cpp :: C++ String Length Example |
Cpp :: how to debug c++ code in vs studio code |
Cpp :: cin.getline |
Cpp :: c++ fstream |
Cpp :: how to dynamically allocate an array c++ |
Cpp :: c++ pause linux |
Cpp :: function c++ |
Cpp :: print a string with printf in c++ |
Cpp :: c++ array size |
Cpp :: even and odd sum in c++ |
Cpp :: how to input a vector when size is unknown |
Cpp :: c++ double is nan |
Cpp :: reverse level order traversal |
Cpp :: power of two c++ |
Cpp :: how to square a number in c++ |
Cpp :: how to add external library in clion |
Cpp :: check prime cpp gfg |
Cpp :: power function c++ |
Cpp :: c define |
Cpp :: max two numbers c++ |
Cpp :: c++ program to convert kelvin to fahrenheit |
Cpp :: reversing a string in c++ |
Cpp :: joining two vectors in c++ |
Cpp :: c++ program to convert character to ascii |
Cpp :: how to use a non const function from a const function |
Cpp :: c++ template |
Cpp :: iostream c++ |
Cpp :: toString method in c++ using sstream |
Cpp :: how to make a vector in c++ |
Cpp :: array copx c++ |