adding up factors of a number

Page 1 of 1

1 Replies - 887 Views - Last Post: 11 December 2012 - 07:39 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=303581&amp;s=7e799bbee37ea956deeb6c90574dea5c&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 tbanks1

Reputation: 0
• Posts: 1
• Joined: 11-December 12

adding up factors of a number

Posted 11 December 2012 - 07:22 AM

```
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int sum;
b = 0;
sum = 1;

cout<<"Enter integer, a:";
cin>>a;

for(b=2;b<=a;b++)
{
if (a % b ==0 )
{ sum+=b; }
}
cout<< "Sum of all factors of a equals= "<< sum <<endl;
return 0;
}

```

I am trying to write a code that will add up all divisors of any number, i have created this code but am stuck on how to make it work for 0 and negative numbers, not sure where to add to the code.

Is This A Good Question/Topic? 0

Replies To: adding up factors of a number

#2 ihatesegfault

Reputation: 17
• Posts: 47
• Joined: 24-September 12

Re: adding up factors of a number

Posted 11 December 2012 - 07:39 AM

you could put this in.
```   if(a!=0) {
if(a<0) {
a=-a;
sum--;
}
} else {
sum = 0;
}
// print stuff out

```

also, in your for loop you only have to go to
```ceil(sqrt(a))
```
.