Euler3: Floating point exception core dumped

Ravi Source

I am executing the following program in C and am getting an error: Floating Point Exception (core dumped). I removed the zero division error I had before and I am kinda stuck here. Thanks in advance for any pointers.

void main()
{
    int i=0;
    long long int num=600851475143;

    for(i=1;i<num/2;i++)
    {
        if((num%i)==0)
        {
            for(int j=1;j<i/2;j++)
            {
                if((i%j)!=0)
                    printf("%d, ",i);
                else break;
            }
        }
    }
}
cgcc

Answers

answered 3 months ago Ravi #1

Used limits.h and small changes to solve the issue. My Code currently:

#include <limits.h>
#include <stdio.h>

int main () {

    long long int res=0, i=2;
    long long int num=600851475143;

    while (num!=1) {

        if (num%i==0) {

            while (num%i==0) {
                printf ("%lld\t", i);
                num/=i;
            }

            res=i;
        }

        i++;
     }

    printf ("\n\nThe largest prime factor is : %lld\n\n", res);

    return 0;
}

answered 3 months ago coderredoc #2

A significant thing you can do is

  • Make long long int num=600851475143LL;. That LL suffix ensures that it is not of type int.

  • The for loop indexing variables should be long long too.

These two changes will make sure there won't be case of overflow which would lead to undefined behavior.

And also make sure in any case you don't hit division by 0 (Also make sure you are using % correctly with correct operands). Use break point when the code breaks. That will help you solve the issue.

comments powered by Disqus