Jump to content



Welcome to KnowledgeSutra - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!
- - - - -

Need Help With C Program To Test If A Number Is Prime


18 replies to this topic

#1 beeseven

    Privileged Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 629 posts

Posted 04 February 2006 - 11:28 PM

#include <stdio.h>

main()
{
	  printf("Enter a number: ");
	  
	  int n;
	  scanf("%d", &n);
	  
	  if(n == 2)
		   printf("%d is prime", n);
	  else if(n % 2 == 0 || n < 2)
		   printf("%d is not prime", n);
	  else
	  {
		   int x;
		   for(x = 0; x < (int)sqrt((double)n); x++)
				if(n % x == 0)
				{
					 printf("%d is not prime", n);
					 return;
				}
		   printf("%d is prime", n);
	  }
}

If n is 2, less than 2, or a multiple of 2, then the program runs fine. Otherwise, I get told that it encountered a problem. I'm kind of new to C, so I'm not exactly sure what's wrong. My background is in Java =/

Can anybody see anything that may be causing the problem?

#2 Unregistered 015

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 276 posts

Posted 04 February 2006 - 11:44 PM

Problem is in this part:

View Postbeeseven, on Feb 5 2006, 01:28 AM, said:

	  else
	  {
		   int x;
		   for(x = 0; x < (int)sqrt((double)n); x++)
				if(n % x == 0)
				{
					 printf("%d is not prime", n);
					 return;
				}
		   printf("%d is prime", n);
	  }
}

I can't tell exactly where since I dont have a compiler and time to analyse it now. Tell me what kind of message you get as return error and it might go smoothly....
It's probably somewhere in this for loop.

#3 BuffaloHelp

    Sterling Archer

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 4,088 posts
  • Gender:Male
  • myCENT:50.18

Posted 05 February 2006 - 12:08 AM

View Postbeeseven, on Feb 4 2006, 06:28 PM, said:

		   int x;
		   for(x = 0; x < (int)sqrt((double)n); x++)
				if(n % x == 0)
I'm assuming I still remember how C's FOR LOOP works. You are dividing by zero as the first step. Therefore, it does not work. Your initial value of x is zero, and you're doing n % x == 0 which will not execute. And THEN it checks to see x < ...etc and add 1 value to x. But since it tried to divide by zero, this loop will stop to protect your computer from hanging.

#4 beeseven

    Privileged Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 629 posts

Posted 05 February 2006 - 12:30 AM

Oh yeah >_< I forgot the first rule of a prime checker: start the loop at 3 and increment by 2.

#5 BuffaloHelp

    Sterling Archer

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 4,088 posts
  • Gender:Male
  • myCENT:50.18

Posted 08 February 2006 - 11:32 AM

Since I don't have C or C++ complier anymore, I tried to do my own coding...but failed miserably so I searched the web to find some helpful tips and formulas.

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Prime Number</title>
</head>

<body>
     <script LANGUAGE="JavaScript">

<!-- Begin

function calculate(form) {

var num=parseInt(form.number.value);

if (isNaN(num) || num < 0) {

form.result.value=(form.number.value + " is not a valid number!  Try again!");

}

if (num == 1) {

form.result.value=("1 is not prime by definition!");

}
if (num == 0) {

form.result.value=("0 is not a valid number.");

}
if (num == 2) {

form.result.value=("2 is a prime number!");
}



for (var i=2;i<num;i++) {

if (num % i == 0) {

var prime="yes";

form.result.value=(num + " is not prime.  It is divisible by " + i + ".");

break;

}

if (num % i != 0) var prime="no";

}

if (prime == "no") form.result.value=(num + " is prime!");

} 

// End -->

     </SCRIPT>
      <P align="left"> 
      <div align="left"> 
        <table width="100%" border="0" cellspacing="2" cellpadding="2">
          <tr> 
            <td> 
              <div align="left"><font size=6><font size="+2" align=RIGHT color="#0000FF"><font color="#CC6600" size="+1">Prime 
                Number</font></font><br>
                </font> 
                <table border=0 width=486 cellpadding=3 cellspacing=0>
                  <tr> 
                    <td>Enter a number and the Prime Number Calculator will instantly 
                      tell you if it is a prime number or not.</td>
                  </tr>
                </table>
              </div>
              <form name=form>
                <div align="left"> 
                  <p>Please enter a number: 
                    <input type=text name=number size=10>
                    <br>
                    <input type=button value="Is it prime?" onClick="calculate(this.form)" name="button">
                    <input type=text name=result size=45 value="">
                    <br>
                  </p>
                </div>
              </form>
            </td>
          </tr>
          <tr> 
            <td>Prime numbers are positive, non-zero numbers that have exactly 
              two factors -- no more, no less.</td>
          </tr>
        </table>
      </div>
</body>

</html>
Try to see if you can use this to reverse engineer your For Loop.

#6 saga

    Premium Member

  • Kontributors
  • PipPipPipPipPipPipPipPip
  • 165 posts

Posted 09 February 2006 - 06:53 AM

View Postciroxyz, on Feb 5 2006, 07:44 AM, said:

Problem is in this part:
I can't tell exactly where since I dont have a compiler and time to analyse it now. Tell me what kind of message you get as return error and it might go smoothly....
It's probably somewhere in this for loop.

int n;
int i;
int isPrime = 1; //1 is true and 0 is for false, there is no boolean in C not like C++
//it should be set initialy to true
for(i=n;i>1;i--)
{
if(n%i==0)
{
isPrime = 0;//set to false if n is evenly divisible
break; //then exit the loop leaving isPrime == false
}
}

if(isPrime) printf("It is a prime number.");
else printf("it is not a prime number.");

i think this one will work, but if you already solved the problem it is still useful becuase its a diferent method cmpared to yours..

by the way this code does not work with 2 it only works for 3 and above..

good luck...

#7 mama_soap

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 282 posts
  • Gender:Female
  • Location:Bangalore

Posted 27 February 2006 - 09:59 PM

@Saga: Your program will take fractionally longer to run, because you loop through all the cases (if I understand correctly), which is not really necessary. Some simple math will tell you that looping through 1 to sqrt(n) is enough to detect if n is prime or not. So you can optimize your program performance. I know this sounds like I'm being picky, but when you're testing if 352224t657723242366667 is a prime or not, it does make a difference :lol:

@beeseven: Providing the exact error message would help - although, for starters, I think I'm missing the opening and closing flower-braces under the for loop. Can you check that up? Other than that, I really don't see why the code shouldn't work...

#8 beeseven

    Privileged Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 629 posts

Posted 28 February 2006 - 01:17 AM

It does, I posted that I solved my problem 23 days ago.

#9 BuffaloHelp

    Sterling Archer

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 4,088 posts
  • Gender:Male
  • myCENT:50.18

Posted 28 February 2006 - 01:35 AM

Issue resolved and topic is now closed.

#10 iGuest

    Hail Caesar!

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 5,876 posts
  • Interests:Trap17 Free Web Hosting, No Ads

Posted 12 November 2007 - 03:06 PM

#include <stdio.h>

main()
{
printf("Enter a number: ");

int n;
scanf("%d", &n);

if(n == to)
printf("%d is prime", n);
else if(n % to == 0 || n < to)
printf("%d is not prime", n);
else
{
int x;
for(x = 0; x < (int)sqrt((double)n); x++)
if(n % x == 0)
{
printf("%d is not prime", n);
return;
}
printf("%d is prime", n);
}
}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users