Link to home
Start Free TrialLog in
Avatar of burnedfaceless
burnedfaceless

asked on

Finding Divisors

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

Avatar of phoffric
phoffric

float f = number:

Try using f instead of number when calculating result.
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

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
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
ASKER CERTIFIED SOLUTION
Avatar of sarabande
sarabande
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial