G'Day guys,

Being working on some code, and was just wondering if there are any obvious places i have gone wrong. I am trying to make 2 functions, 1 that will find the factors of a given number, and the other function to find the percentage of the even factors.
E.g. 12: factors = 1,2,3,4,6,12 even factors = 2,4,6,12
so the percentage of even factors is = (4/6)*100
any help is always appreciated.

to find the factors:

int factors (int number)
{
    for(int i=1; i<=number; i++)
      {
         if(number%i==0) 
         {
            if (i%2==0) 
            {
              return i;
            }
         }
      }
}

and.. to find the percentage of even factors

int percentageOfEvenFactors (int number)
{
    int percentage=0;
    int allFactors;
    int evenFactors=0;
    for (int i=1; i<=number; i++)
    {
        if (number%i==0)
        {
           i=allFactors;
                        
          if(i%2==0)
          {
            evenFactors++;
          }
          percentage=(allFactors/evenFactors)*100;
        }
    }
    cout<<percentage<<endl;
}

Cheers.

My mind is a little bit rusty, so I can't think what this line should be, but I know that it should not be this:

i=allFactors;

You're assigning i some random crap that's contained in allFactors , because you never initalized it. Perhaps you want

allFactors++;

?
But you'll still have to initalize allFactors with 0 or something.

Another interesting problem:

int percentageOfEvenFactors (int number)
{
    int evenFactors=0;

And then...

percentage=(allFactors/evenFactors)*100;

NO NO NO! You're dividing by zero, which will cause the program to crash!

I think you got it backwards (don't you want evenFactors/allFactors?). And the percentage should only be calculated after the for() loop, not in it. That will prevent division from 0.

Hope this helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.