Jump to content
xisto Community
beeseven

Need Help With C Program To Test If A Number Is Prime Ending unexpectedly somewhere near for-loop

Recommended Posts

#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?

Share this post


Link to post
Share on other sites

Problem is in this part:

	  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.

Share this post


Link to post
Share on other sites

		   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.

Share this post


Link to post
Share on other sites

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"><!-- Beginfunction 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.

Share this post


Link to post
Share on other sites

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...

Share this post


Link to post
Share on other sites

@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...

Share this post


Link to post
Share on other sites

#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); }}

Share this post


Link to post
Share on other sites

plz print prime no from 1 to 100

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

 

Please print prime no from 1 to 100

 

 

Its my assiment I have to complete it

 

-reply by syed jawwad alam

Share this post


Link to post
Share on other sites

object of a class

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

 

I just want to know the javacoding to create object of a class.

 

-reply by suro

Share this post


Link to post
Share on other sites

c program that test numbers

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

 

Assignment Description

 

Develop a program using the C language that will use a single subscripted array to solve the following problem. Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print it only if it is NOT a duplicate of a number already read. At the end the program should give a summary of how many numbers were entered and how many numbers were rejected and how many numbers were displayed.

 

Your program should use functions.

 

1. Function Readnum

Your program should prompt the user to input up to 20 numbers. [15 points]

 

2. Function Testnum

Next the program should test if the number has already been entered or not. If not, the number should be displayed

 

3. Function Summary

Finally the program should display the summary as follows;

Total numbers entered

Total numbers rejected because they were duplicates

Total numbers displayed

 

 

-question by Naemi Ngeno

Share this post


Link to post
Share on other sites

#include<stdio.H>#include<conio.H>#define PRIME 1#define NON_PRIME 0Void main(){int and,flag,I;Clrscr();Printf("Enter number:");Scanf("%d",&and);Flag=PRIME;    /* Assume Number is always PRIME */For(I=2;I<and;I++)  { if(and%I==0)    flag=NON_PRIME;  }if(flag==PRIME)  printf("and%d is PRIME",and);Else  printf("and%d is NOT PRIME.",and);getch();}

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.