Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

javascript Sum of all the factors of a number

<script>
    // Find sum of all divisors
// of a natural number
 
// Function to calculate sum of all
//divisors of a given number
function divSum(n)
{
    if(n == 1)
      return 1;
 
    // Sum of divisors
    let result = 0;
 
    // find all divisors
    // which divides 'num'
    for ( let i = 2; i <= Math.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 Code
let n = 30;
document.write(divSum(n));
 
// This code is contributed by _saurabh_jaiswal.
</script>
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #javascript #Sum #factors #number
ADD COMMENT
Topic
Name
7+4 =