Sum of all the factors of a number - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Sum of all the factors of a number
Sum of all proper divisors of a natural number
Sum of all divisors from 1 to n
Find all divisors of a natural number | Set 2
Find all factors of a natural number | Set 1
Count Divisors of n in O(n^1/3)
Total number of divisors for a given number
Write an iterative O(Log y) function for pow(x, y)
Write a program to calculate pow(x,n)
Modular Exponentiation (Power in Modular Arithmetic)
Modular exponentiation (Recursive)
Modular multiplicative inverse
Euclidean algorithms (Basic and Extended)
Program to find GCD or HCF of two numbers
Program to find LCM of two numbers
LCM of given array elements
Finding LCM of more than two (or array) numbers without using GCD
GCD of more than two (or array) numbers
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Segmented Sieve
Segmented Sieve (Print Primes in a Range)
Prime Factorization using Sieve O(log n) for multiple queries
Efficient program to print all prime factors of a given number
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Sum of all the factors of a number
Sum of all proper divisors of a natural number
Sum of all divisors from 1 to n
Find all divisors of a natural number | Set 2
Find all factors of a natural number | Set 1
Count Divisors of n in O(n^1/3)
Total number of divisors for a given number
Write an iterative O(Log y) function for pow(x, y)
Write a program to calculate pow(x,n)
Modular Exponentiation (Power in Modular Arithmetic)
Modular exponentiation (Recursive)
Modular multiplicative inverse
Euclidean algorithms (Basic and Extended)
Program to find GCD or HCF of two numbers
Program to find LCM of two numbers
LCM of given array elements
Finding LCM of more than two (or array) numbers without using GCD
GCD of more than two (or array) numbers
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Segmented Sieve
Segmented Sieve (Print Primes in a Range)
Prime Factorization using Sieve O(log n) for multiple queries
Efficient program to print all prime factors of a given number
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Difficulty Level :
Medium
Given a number n, the task is to find the sum of all the factors.Examples :  
Input : n = 30
Output : 72
Dividers sum 1 + 2 + 3 + 5 + 6 + 
             10 + 15 + 30 = 72 

Input :  n = 15
Output : 24
Dividers sum 1 + 3 + 5 + 15 = 24
 
A simple solution is to traverse through all divisors and add them.  
C++
Java
Python3
C#
PHP
Javascript
// 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 numberint 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 caseint main(){    int n = 30;    cout << divSum(n);    return 0;}
// Simple Java program to// find sum of all divisors// of a natural numberimport java.io.*; class GFG {     // Function to calculate sum of all    //divisors of a given number    static int divSum(int n)    {         if(n == 1)           return 1;        // Final result of summation        // of divisors        int result = 0;             // find all divisors which divides 'num'        for (int 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 program to run the case    public static void main(String[] args)    {        int n = 30;        System.out.println(divSum(n));    }} // This code is contributed by Prerna Saini.
# Simple Python 3 program to# find sum of all divisors of# a natural numberimport math  # Function to calculate sum# of all divisors of given#  natural numberdef divSum(n) :    if(n == 1):       return 1     # Final result of summation    # of divisors    result = 0       # find all divisors which    # divides 'num'    for i in range(2,(int)(math.sqrt(n))+1) :         # if 'i' is divisor of 'n'        if (n % i == 0) :             # if both divisors are same            # then add it only once            # else add both            if (i == (n/i)) :                result = result + i            else :                result = 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 casen = 30print(divSum(n)) # This code is contributed by Nikita Tiwari.
// Simple C# program to// find sum of all divisors// of a natural numberusing System; class GFG {     // Function to calculate sum of all    //divisors of a given number    static int divSum(int n)    {        if(n == 1)           return 1;         // Final result of summation        // of divisors        int result = 0;             // find all divisors which divides 'num'        for (int 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 program to run the case    public static void Main()    {                 int n = 30;                 Console.WriteLine(divSum(n));    }} // This code is contributed by vt_m.
<?php// Find sum of all divisors// of a natural number // Function to calculate sum of all//divisors of a given numberfunction divSum($n){    if($n == 1)      return 1;     // Sum of divisors    $result = 0;     // find all divisors    // which divides 'num'    for ( $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 Code$n = 30;echo divSum($n); // This code is contributed by SanjuTomar.?>
<script>    // Find sum of all divisors// of a natural number // Function to calculate sum of all//divisors of a given numberfunction 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 Codelet n = 30;document.write(divSum(n)); // This code is contributed by _saurabh_jaiswal.</script>
Output :  
72
An efficient solution is to use below formula. Let p1, p2, ... pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (p1a1)*(p2a2)* ... (pkak).  
Sum of divisors = (1 + p1 + p12 ... p1a1) * 
                  (1 + p2 + p22 ... p2a2) *
                  .............................................
                  (1 + pk + pk2 ... pkak) 

We can notice that individual terms of above 
formula are Geometric Progressions (GP). We
can rewrite the formula as.

Sum of divisors = (p1a1+1 - 1)/(p1 -1) * 
                  (p2a2+1 - 1)/(p2 -1) *
                  ..................................
                  (pkak+1 - 1)/(pk -1)
How does above formula work?  
Consider the number 18.  

Sum of factors = 1 + 2 + 3 + 6 + 9 + 18

Writing divisors as powers of prime factors.
Sum of factors = (20)(30) + (21)(30) + (2^0)(31) +
                 (21)(31) + (20)(3^2) + (2^1)(32)
               = (20)(30) + (2^0)(31) + (2^0)(32) +
                 (21)(3^0) + (21)(31) + (21)(32)
               = (20)(30 + 31 + 32) + 
                 (21)(30 + 31 + 32)
               = (20 + 21)(30 + 31 + 32)
If we take a closer look, we can notice that the
above expression is in the form.
(1 + p1) * (1 + p2 + p22)
Where p1 = 2 and p2 = 3 and 18 = 2132
So the task reduces to finding all prime factors and their powers.  
C++
Java
Python3
C#
PHP
Javascript
// Formula based CPP program to// find sum of all  divisors of n.#include <bits/stdc++.h>using namespace std; // Returns sum of all factors of n.int sumofFactors(int n){    // Traversing through all prime factors.    int res = 1;    for (int i = 2; i <= sqrt(n); i++)    {                  int curr_sum = 1;        int curr_term = 1;        while (n % i == 0) {             // THE BELOW STATEMENT MAKES            // IT BETTER THAN ABOVE METHOD            //  AS WE REDUCE VALUE OF n.            n = n / i;             curr_term *= i;            curr_sum += curr_term;        }         res *= curr_sum;    }     // This condition is to handle    // the case when n is a prime    // number greater than 2.    if (n >= 2)        res *= (1 + n);     return res;} // Driver codeint main(){    int n = 30;    cout << sumofFactors(n);    return 0;}
// Formula based Java program to// find sum of all divisors of n. import java.io.*;import java.math.*;public class GFG{         // Returns sum of all factors of n.    static int sumofFactors(int n)    {        // Traversing through all prime factors.        int res = 1;        for (int i = 2; i <= Math.sqrt(n); i++)        {                              int  curr_sum = 1;            int curr_term = 1;                         while (n % i == 0)            {                     // THE BELOW STATEMENT MAKES                // IT BETTER THAN ABOVE METHOD                // AS WE REDUCE VALUE OF n.                n = n / i;                     curr_term *= i;                curr_sum += curr_term;            }                 res *= curr_sum;        }             // This condition is to handle        // the case when n is a prime        // number greater than 2        if (n > 2)            res *= (1 + n);             return res;    }         // Driver code    public static void main(String args[])    {        int n = 30;        System.out.println(sumofFactors(n));    }} /*This code is contributed by Nikita Tiwari.*/
# Formula based Python3 code to find# sum of all divisors of n.import math as m # Returns sum of all factors of n.def sumofFactors(n):         # Traversing through all    # prime factors    res = 1    for i in range(2, int(m.sqrt(n) + 1)):                 curr_sum = 1        curr_term = 1                 while n % i == 0:                         n = n / i;             curr_term = curr_term * i;            curr_sum += curr_term;                     res = res * curr_sum         # This condition is to handle the    # case when n is a prime number    # greater than 2    if n > 2:        res = res * (1 + n)     return res; # driver code   sum = sumofFactors(30)print ("Sum of all divisors is: ",sum) # This code is contributed by Saloni Gupta
// Formula based Java program to// find sum of all divisors of n.using System; public class GFG {         // Returns sum of all factors of n.    static int sumofFactors(int n)    {                 // Traversing through all prime factors.        int res = 1;        for (int i = 2; i <= Math.Sqrt(n); i++)        {                              int curr_sum = 1;            int curr_term = 1;                         while (n % i == 0)            {                     // THE BELOW STATEMENT MAKES                // IT BETTER THAN ABOVE METHOD                // AS WE REDUCE VALUE OF n.                n = n / i;                     curr_term *= i;                curr_sum += curr_term;            }                 res *= curr_sum;        }             // This condition is to handle        // the case when n is a prime        // number greater than 2        if (n > 2)            res *= (1 + n);             return res;    }         // Driver code    public static void Main()    {                 int n = 30;                 Console.WriteLine(sumofFactors(n));    }} /*This code is contributed by vt_m.*/
<?php// Formula based PHP program to// find sum of all divisors of n. // Returns sum of all factors of n.function sumofFactors($n){         // Traversing through    // all prime factors.    $res = 1;    for ($i = 2; $i <= sqrt($n); $i++)    {         $curr_sum = 1;        $curr_term = 1;                 while ($n % $i == 0)        {             // THE BELOW STATEMENT MAKES            // IT BETTER THAN ABOVE METHOD            // AS WE REDUCE VALUE OF n.            $n = $n / $i;             $curr_term *= $i;            $curr_sum += $curr_term;        }         $res *= $curr_sum;    }     // This condition is to handle    // the case when n is a prime    // number greater than 2    if ($n > 2)        $res *= (1 + $n);     return $res;} // Driver Code$n = 30;echo sumofFactors($n); // This code is contributed by Anuj_67.?>
<script>    // Formula based Javascript program to// find sum of all divisors of n. // Returns sum of all factors of n.function sumofFactors(n){         // Traversing through    // all prime factors.    let res = 1;    for (let i = 2; i <= Math.sqrt(n); i++)    {         let curr_sum = 1;        let curr_term = 1;                 while (n % i == 0)        {             // THE BELOW STATEMENT MAKES            // IT BETTER THAN ABOVE METHOD            // AS WE REDUCE VALUE OF n.            n = n / i;             curr_term *= i;            curr_sum += curr_term;        }         res *= curr_sum;    }     // This condition is to handle    // the case when n is a prime    // number greater than 2    if (n > 2)        res *= (1 + n);     return res;} // Driver Codelet n = 30;document.write(sumofFactors(n)); // This code is contributed by _saurabh_jaiswal.</script>
Output :  
72
Further Optimization. If there are multiple queries, we can use Sieve to find prime factors and their powers.References: https://www.math.upenn.edu/~deturck/m170/wk3/lecture/sumdiv.html http://mathforum.org/library/drmath/view/71550.html 
SanjuTomar
vt_m
arupjyoti_dutta
spp____
_saurabh_jaiswal
divisors
number-theory
prime-factor
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Print all possible combinations of r elements in a given array of size n
Program for Decimal to Binary Conversion
The Knight's tour problem | Backtracking-1
Operators in C / C++
Program for factorial of a number
Find minimum number of coins that make a given value
Program to find sum of elements in a given array