Question:
My C program isn't working! for the smallest number that can be divided by the first ten natural no?
transitory
2013-04-30 04:46:38 UTC
Question :

What is the smallest positive number that is evenly divisible(giving remainder as zero) by all of the numbers from 1 to 10?

I did it for 1-10 first,

My program:

#include

int main()

{ int i,l=0,q=0;

int remz(int w,int x);

printf("answers:\n");

for(i=11;1!=l;i++)

l=remz(i,q);

}



int remz(int w,int x)

{ int m=1;

if(w%m==0)

{if(m<11)

{m=m+1;

remz(w,x);}

else

{printf("%d,",w);

x=x+1; return x;} }



}

It's showing a "segmentation fault: 11"


Can you figure out what's wrong?
Three answers:
KIRAN KUMAR
2013-04-30 06:10:20 UTC
Hi,

the code you are using is wrong as it will go to infinite loop because any time the m value will not be 11 as it was local variable. use below code for your requirement



====================================================

#include

int remz(int num, int q, int counter);

int main()

{

int num=0,readscan,q=0, counter = 0;

printf("\n enter range for gettig the numner :");

scanf("%d",&readscan);

printf("The solution is: \n");

for ( num = 11; num<=readscan ; num++)

{

q = 0;

counter = 0;

remz(num,q, counter);

}

return 0;

}

int remz(int num, int q, int counter)

{

if(q<11)

{

q = q+1;

if( num%q == 0 )

{

counter ++;

}

remz( num, q, counter );

}

else

{

if( counter == 10 )

printf("%d is divisible by 1-10\n",num);



}

return 0;

}
cja
2013-04-30 13:24:23 UTC
As previous responders have said, your logic is not correct, and the segmentation fault is due to infinite recursion. When you're writing a recursive function, the first clue that you're on the wrong track is if you have more than a few lines, and too much if-else logic. I think your program should look something like this:



/*

    What is the smallest positive number that is evenly divisible

    (giving remainder as zero) by all of the numbers from 1 to 10?

*/

#include



unsigned long remz(unsigned long, unsigned long);

const unsigned long limit = 11;



int main(int argc, char *argv[]) {

    unsigned long x, z = 0;



    for (x = 1; z < limit; x++) {

        z = remz(x, 1);

    }

    for (z = 1; z < limit; z++) {

        printf("%lu / %lu = %g\n", x - 1, z, (x - 1) / (float)z);

    }

    return 0;

}



/*

    Return the largest number >= y that x can be evenly

    divided by.

*/

unsigned long remz(unsigned long x, unsigned long y) {

    if ((x % y) != 0) return y;

    return remz(x, y + 1);

}



#if 0



Program output:



2520 / 1 = 2520

2520 / 2 = 1260

2520 / 3 = 840

2520 / 4 = 630

2520 / 5 = 504

2520 / 6 = 420

2520 / 7 = 360

2520 / 8 = 315

2520 / 9 = 280

2520 / 10 = 252



#endif
Fred W
2013-04-30 12:00:42 UTC
if remz() recurses, it continues to recurse.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...