1

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.

  • `10.0/9` or `10/9.0` or whatever that makes the expression be evaluated as float rather than an int that is assigned to a float variable. – Wiktor Zychla Sep 06 '20 at 12:35
  • Thank you first of all. But I tried it and it didnt change the result ` float input = 600851475143f; for (float i = 0f; i < 1000.0; i++) { float temp = input/i; if ((temp % 1) == 0) { Console.Write(i + ", "); } } ` – Peter Peperoni Sep 06 '20 at 12:41
  • Use Double not Float so such a high amount – Mosia Thabo Sep 06 '20 at 12:44
  • actually use 64 bit longs and check input % i directly, don't divide first then check modulus 1 – Johnny Andrew Sep 06 '20 at 12:49
  • https://stackoverflow.com/questions/10851273/why-does-integer-division-in-c-sharp-return-an-integer-and-not-a-float – mjwills Sep 06 '20 at 13:22

1 Answers1

2

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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132