Home > OS >  Trying to create a C program which prints out all numbers with rational square roots?
Trying to create a C program which prints out all numbers with rational square roots?

Time:07-09

#include <stdio.h>
#include <cs50.h>
#include <unistd.h>
#include <math.h>

void rationalSquareRoots(void);

int main(void) {
    rationalSquareRoots();
}

void rationalSquareRoots(void) {
    for(float i = 0; ; i  ) {
    if(sqrt(i) % 1 == 0) {
        printf("%f\n", i);
    }
    sleep(1);
    }
}

I've encountered the following problem while attempting to make a program which prints out all numbers with rational square roots (well, all numbers up to the point of overflowing, I guess).

14:19: error: invalid operands to binary expression ('double' and 'int')
    while(sqrt(i) % 1 == 0) {

The problem seems to be in the % operator? Is it not supported in if statements? What's the solution?

CodePudding user response:

The % operator is only for divisions between integers.

To calculate remainders of floating-point divisions, you should use fmod() function.

Using this function, the condition should be fmod(sqrt(i), 1) == 0.

CodePudding user response:

The error is caused by the fact the modulo (%) is defined only for integers in C and C . sqrt(i) returns a double (which it should, as square roots of integers can have infinite decimal digits), hence causing an error.

You can totally do what you're doing here, with use of the fmod function instead.

However, I will also offer an alternative implementation which, in terms of time complexity, is much more efficient. Instead of iterating through the integers and checking if their square roots are rational, simply output the square numbers.

I understand that you may be doing this as a practice for the C operators (or practice for C in general), but maybe someone will find this useful.

void rationalSquareRoots(void) {
    for(float i = 0; ; i  ) {
        printf("%f\n", i*i);
//        sleep(1);
          sleep((i 1)*(i 1)-i*i); //to give the same behaviour as your provided code
    }
}
  • Related