1 Replies - 444 Views - Last Post: 11 December 2012 - 07:39 AM Rate Topic: -----

#1 tbanks1  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

  • New D.I.C Head

Reputation: 17
  • View blog
  • 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--;
       }
       // your for loop
   } else {
     sum = 0;  
   }
   // print stuff out



also, in your for loop you only have to go to
ceil(sqrt(a))
.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1