Finding Divisors

burnedfaceless
burnedfaceless used Ask the Experts™
on
In the code below it is not registering float values - for example if it divides 4 by 3 it is registering 1 as an answer (if you enter 4 when it loops up to 3 it doesn't record the float value).

I want to store the float value so I can see if it is a divisor or not.

#include <iostream>
#include <cmath>

bool is_integer(float number) {
  return std::floor(number) == number;
}

int divisors(int number) {
  int i = 1;
  float result;
  for (i = 1; i<= number; i++) {
    result = number / i;
    std::cout << i;
    std::cout << result;
    std::cout << "\n";
  }
}

int main()
{
  int counter = 1;
  int number;
  int number_divisors;

  std::cout << "Enter a number to find the divisors";
  std::cin >> number;

  number_divisors = divisors(number);




  return 0;
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
float f = number:

Try using f instead of number when calculating result.
Dr. KlahnPrincipal Software Engineer

Commented:
Integer math will do this job faster than floating point.  Only numbers up to the square root of the number under test must be examined.  Example pseudocode below ...

for k = 2 to sqrt(testnumber)
  if [testnumber mod k) == 0] {
    print (k, "is a factor of", testnumber)
    print (testnumber/k, "is a factor of", testnumber)
  }
next k

Open in new window

Top Expert 2016

Commented:
result = number / i;
you could make it 2 statements as suggested by phoffric or do

result = ((float)number )/ i;

Open in new window


this would 'cast' the nominator to float and the division result is float as well.

Sara
trinitrotolueneDirector - Software Engineering

Commented:
number_divisors = divisors(number);

Open in new window


you seem to be expecting divisors() to return something but I don't see a return statement in the function.

float result;
  for (i = 1; i<= number; i++) {
    result = number / i;
    std::cout << i;
    std::cout << result;
    std::cout << "\n";
  }
}

Open in new window


also if you are trying to count divisors the logic you've used is not going to do any counting..... for that you have to do what Dr.Klahn has suggested
Top Expert 2016
Commented:
if you are trying to count divisors the logic you've used is not going to do any counting

you could make your code work correct like with the following:

int divisors(int number) {
  int i = 1;
  float result;
  int count = 0;
  for (i = 2; i<= number/i; i++) {
    result = ((float)number) / i;
    if ((number/i)*i == number) {
       count++;
       std::cout << i "  is divisor of " << number << std::endl;
    }
    std::cout << i << " " << result << std::endl;

  }
  return count;
}

Open in new window


Sara

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial