recursion and switch to look for prime numbers

recursion and switch to look for prime numbers

Page 1 of 1

1 Replies - 2446 Views - Last Post: 17 June 2009 - 01:34 AM Rate Topic: -----

#1 alvaroe  Icon User is offline

  • New D.I.C Head

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

recursion and switch to look for prime numbers

Post icon  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
//		 start with the next num


		 } // 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  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 26
  • View blog
  • 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?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1