Peter Peperoni
Peter Peperoni

Reputation: 80

Float Evaluation returns integer?

I recently started with the euler Project for practice, I completed 1 and 2, but 3 is just not working. I used the same line of code for every solution to check if the number is decimal or not. This worked fine except this time, but I dont know why. This code

            for (float i = 0; i < 1000; i++)
            {
                float temp = i / 3;
                float temp2 = i/ 5;
                if ((temp % 1) == 0 || (temp2 % 1) == 0)
                {
                    num += i;
                }
            }

worked perfectly fine, but this one (which is basically the same)

float input = 600851475143;
for (float i = 0; i < 1000; i++)
        {
            float temp = input/i;
            if ((temp % 1) == 0)
            {
                Console.Write(temp + ", ");
            }

just returns every number. Then I tried this

float temp = 10/9;
Console.WriteLine(temp);

But it just returns 1. So i thought of an overflow or something like that, but my next approach didnt work either:

float temp = 10/9;
bool temp2 = (temp%1) == 0;
Console.WriteLine(temp2);

Return: True

I dont now what to do anymore, does someone know why this happens? Thanks in advance.

Upvotes: 1

Views: 182

Answers (1)

Guru Stron
Guru Stron

Reputation: 143373

float in C# has precision of 6-9 digits according to docs, 600851475143 divided by maximum i in the loop (i.e. 999) will have more than 9 digits in mantissa so float will not be able to cover fractional part, so try switching to double or even decimal:

double input = 600851475143;
for (double i = 0; i < 1000; i++)
{
    double temp = input / i;
    if ((temp % 1) == 0)
    {
        Console.Write(temp + ", ");
    }
}

Also I would say that you can use long's in this case:

long input = 600851475143;
for (long i = 1; i < 1000; i++)
{
    var x = (input % i);
    if (x == 0)
    {
        Console.WriteLine(input / i);
    }
}

As for the last snippet - 10 and 9 in 10/9 are int's, so the result of 10/9 is an int and equals to 1, which give you the result you get.

Upvotes: 2

Related Questions