recursion and switch to look for prime numbers

Page 1 of 1

1 Replies - 4411 Views - Last Post: 17 June 2009 - 01:34 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=110444&amp;s=37099038ebee15b12cc75e11a617a91d&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

#1 alvaroe

Reputation: 0
• Posts: 1
• Joined: 17-June 09

recursion and switch to look for prime numbers

Posted 17 June 2009 - 12:41 AM

Hello everybody,

anticipated thanks to anyone who reads it.

I have thought up this code for solving whether a number is prime or not. If it is not, it should go up to a number above and see if that one is, so as to in recursion. You will see, that in order to avoid the infinite loop I am using a flag. Because the code of the recursion would be accessed in both cases whether the check said it was or not a prime number, I use that flag. You will see that in my switch, if it is not divisible by any of the 2,3,5,7 numbers, then it is a prime number the flag changes value and thus, it would not go to the recursion, just finish the script. While it compiles fine, it does give error 1 whe running it. I am puzzled because , in my substandard intelligence, this code makes sense....to me...

```#include <stdio.h>

int primos (int num); // function prototype

int main (void) {
int num, divisor;
int flag = 1;

printf ("Enter a number: ");
scanf ("%d", &num); // yes, i know there are more formal ways to get input...

int primos (num) { // THIS IS THE FUNCTION

switch (divisor) {
case 2:
if (num % divisor == 0)
break;
case 3:
if (num % divisor == 0)
break;
case 5:
if (num % divisor == 0)
break;
case 7:
if (num % divisor == 0)
break;
default:
printf ("This is a prime number %d\n", num);
flag = 0;

//		 if none of the cases applies, then it is a prime number. If any applies, that is, it has a remainder of 0, leave the switch and

} // END OF SWITCH

if (flag != 0) { // that is, it left the switch at some "break" place...
num += 1;
primos (num );
}

} // END OF THE FUNCTION

}

```

Is This A Good Question/Topic? 0

Replies To: recursion and switch to look for prime numbers

#2 BlakeJustBlake

• D.I.C Regular

Reputation: 26
• Posts: 441
• Joined: 15-February 09

Re: recursion and switch to look for prime numbers

Posted 17 June 2009 - 01:34 AM

What's the error?