May 16, 2008

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

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > C/C++ Programming
Pages: 1, 2

free web hosting

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

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

 

 

 


Reply

Unregistered 015
Problem is in this part:

QUOTE(beeseven @ Feb 5 2006, 01:28 AM) *

CODE

      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.

 

 

 


Reply

BuffaloHELP
QUOTE(beeseven @ Feb 4 2006, 06:28 PM) *

CODE

           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.

Reply

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

Reply

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

Reply

saga
QUOTE(ciroxyz @ Feb 5 2006, 07:44 AM) *

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

Reply

mama_soap
@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 laugh.gif

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

Reply

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

Reply

BuffaloHELP
Issue resolved and topic is now closed.

Reply

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

Reply

Latest Entries

Trap FeedBacker
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

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Pages: 1, 2
Recent Queries:-
  1. c program to test for prime number - 2.59 hr back.
  2. "is it prime" pascal - 2.75 hr back.
  3. prime number between in c program - 14.46 hr back.
  4. prime number program in c - 16.94 hr back.
  5. shortest c program prime no - 17.11 hr back.
  6. prime no program c - 17.56 hr back.
  7. c code for finding a prime number - 18.29 hr back.
Similar Topics

Keywords : c, program, test, number, prime, ending, unexpectedly, loop

  1. Any Program Ideas?!
    (5)
  2. Most Efficient Code To Get Prime Numbers
    (7)
    Can anyone write a more efficient code than this to get the prime numbers from 1 -999? //
    Assignment: sieve.cpp // Purpose: To write the most efficient program // that outputs prime
    numbers. #include #include #include // declare constant MAX_NUMBER to be the # of arrays. const
    MAX_NUMBER = 1000; // declare array primes. bool primes ; // function prototypes void
    initializeArray(); void findMultiples(); void printSubscripts(); int main() { // call to functions
    initializeArray(); findMultiples(); printSubscripts(); return 0; }
    //*****************************....
  3. How To Run A Process Through Your Program (c#)
    (0)
    Made by Blackbelt012 OK to start add a button or a menu strip to your form.
    ----------------------------------- Then double click the button you just added and it will take you
    to the code of your application. ----------------------------------- Next scroll to the very top of
    your form and add this code. CODE using System.Diagnostics;
    ----------------------------------- Then scroll back down to the button you double clicked.
    ----------------------------------- After that add this code. CODE
    Process.Start(@"C:\Program Files\Mozil....
  4. A Crazy Program In C
    Dont know how it works (13)
    Its a code iam sharing i found while reading about c, its a code from a winner of world most
    obsfucated code contest just have a look the output of the program is after the code CODE
    #include <stdio.h> main(t,_,a) char *a;
    {return!0<t?t<3?main(-79,-13,a+main(-87,1-_, main(-86, 0, a+1
    )+a)):1,t<_?main(t+1, _, a ):3,main ( -94, -27+t, a )&&t ==
    2 ?_<13 ?main ( 2, _+1, "%s %d %d\n"
    ):9:16:t<0?t<-72?main(_, t,"@n'+,#'/*{}w+/w#cdnr....
  5. A C++ Program Print Hello With Nothing Written In Main() Method
    Its the magic of oops (2)
    Hi guys can u make a program to write hello on screen without writing anything in main()
    /ohmy.gif" style="vertical-align:middle" emoid=":o" border="0" alt="ohmy.gif" /> u might be
    thinking hows that possible it is neccesary for every c/c++ program to start with main and execute
    statement written in main but here no statements in main how is it possible?,dont worry it is
    possible ill show u how: CODE #include<stdio.h> #include<iostream.h> class
    hello     {         int a;         public:              hello(){cout<<"hel....
  6. How I Shall Scan Prime Numbers..
    that is 1,3,5,7,11,13,17,19... (4)
    I want to scan prime numbers ,have you logic to solve this problem? here is example of even
    numbers: CODE
    ----------------------------------------------------------------------------------------------------
    ---------- void main (void) {clrscr(); int a; printf("input any
    no."); scanf("%d"&a); if(a%2=0) {printf("the number is
    even"); getch(); }
    ----------------------------------------------------------------------------------------------------
    -------- Now I want to scan prime numbers....
  7. C Or C++ Easy Programming Generator
    You need a program? (6)
    Hi i just had a stupid question on how to program is C or C++. I would like to know if there is any
    program like Photoshop to create C codes or how to put them together. If someone could show me it
    would be great. I appreciate it as i love computers and want to be like a wiz at it and also
    everything related to it. I know that this is crazy and i have heard that from people they tell me
    you're a GFX person stay there but i want to explore. Thanks if helped.....
  8. Buffer Overflow In Action Tutorial
    Learn how to buffer overflow programs to change the program flow... (0)
    This tutorial will show you how to buffer overflow programs in order to change the flow of the
    application , even if this means executing your own code. A very well explained tutorial of buffer
    overflows ( not theory but practise ) + a 20 min video tutorial/demonstration + all the files needed
    for the tutorial.. Buffer Overflow In Action Tutorial LINK ....
  9. Centering The Text In A Simple C++ Program?
    (8)
    I'm currently learning C++ in college. For now it's very basic stuff (cout, cin, if, switch,
    voids, etc). But I'm also abit of a "must look neat" freak for certain things. One of which is
    that I don't like the text on the program being aligned to the right. For example, I currently
    have something like this: QUOTE Welcome! Please enter your first name. __ And what's
    your second name? __ But I want it to be like this: QUOTE Welcome! Please enter your
    first name. __ And what's your second name? __ My question is simply:....
  10. Program Lang I Know
    Turbo pascal (2)
    well well.... /laugh.gif" style="vertical-align:middle" emoid=":lol:" border="0" alt="laugh.gif"
    /> what can i say? its an old lang. uses the dos functions and is dos based. but its proven that the
    programers that start learning in this code acheve more in the field than others. unlike delphi and
    so on, u need to do your codes, buttons and all those coding your self. no short ways and no error
    skiping. if the program encounters an error it wont run until you fixed it. i would like to know
    who else uses this lang or who knows this lang.....
  11. Source Code For Paint Like Program Under Dos In C
    (2)
    this is a dos program that you have been waiting for you learn from it you how to do graphic
    programing under dos if you understand it your then will be able to do any kind of windows GUI in
    dos it make icons and use them it deal with graphic file youwill also learn how to use mouse have
    nice time ....
  12. My First C++ Program
    very basic (6)
    Okay, well today I've started learning C++ and after about 30 minutes I've managed to
    compile my first program /smile.gif" style="vertical-align:middle" emoid=":)" border="0"
    alt="smile.gif" /> All it does is prompt you to type a number in between 1 and 10. If it's not
    in that range, it adds/subtracts until it is. The best part is you get to see it add/subtract the
    numbers up one-by-one! Code: #include using namespace std; int main() {
    // Define variables int anumber; cout cin>> anumber; cin.ignore....
  13. Executing An Exe From Within A Program!
    Need help with my project (6)
    Hello everyone, I need help, I need to know which function , or a user defined one should i use to
    call a exe from within a program, Like i use switch cases , it certain condition is encountered the
    exe should gets executed, that is what i want to do, I am making an operating system for my projects
    at university, I need that thing. So somebody please help me, This is the forum that lets me find
    all my solutions. I have a 100% problem solution rate here, everyone has helped me alot, Waiting for
    some one to post a reply.....
  14. Need Debugging Help For A Simple Program
    Just to make sure. (3)
    Hi guys. I just finished my programming homework. It's a program that gets the coefficients
    A,B, and C of two lines in general form and computes for the (1) Slope of each line (2)
    y-intercept of each line (3) and their intersections (if there are any) I know it's quite
    trivial but it's a homework and I need help in making sure the algorithm works for all cases.
    For me, the hardest part is the third one where you have to get the intersections. Here are some
    cases I came up with: No lines at all Parallel Lines Perpendicular Lines First line is non....
  15. Never Ending Books For C++ Programming
    C++ Programming Books (3)
    /smile.gif' border='0' style='vertical-align:middle' alt='smile.gif' /> Hello Friends As I m
    doing MCA so I have so many ebooks for u. Anybody that wants C++ Programming Knowledge ,can get from
    these books,it includes all basic and expert features programming.So here is the collection Only For
    Trap17 Users.If u like this Post Please reply. Thanx ....................
  16. Program From Mekka 97 4k
    mni.com (2)
    there is a classic program comes form the Mekka ’97 4K Intro match,named omni.com,as the best
    works.the size of the program is only 4095 byte...very amazing.it includes many 3D graphics and bg
    music. you could save the code below to 1.txt in you disk(e.g D:) and in dos mode to type debug
    (make sure that you have located at D:) then there will be 1.com out...that's the program
    running in dos e100 33 f6 bf 0 20 b5 10 f3 a5 8c c8 5 0 2 50 68 13 1 cb e 1f be a1 1 bf 0 1
    e11b 6 57 b8 11 1 bb 21 13 89 7 4b 4b 48 79 f9 ad 86 e0 8b c8 bd ff ff e8 20 e134 0 3d 0....
  17. Run A Program From Another One
    (4)
    I have written two programs. Lets call them MAIN and SMALL . Program SMALL is supposed to eventually
    go inside program MAIN. Problem is that if I put the code inside of it, it will be extremely hard to
    read. Can I just compile the program and run it from inside the main one ? I've heard that you
    could. Both programs use identical variables and I wrote it this way intending to cut and paste the
    code into the main one but if I can do this without cutting and pasting 150 KB worth of source code
    then I'd like to learn how. I'm coding in C++ and am using functions....
  18. C++
    C++... a Programmers Program... Or is it? (15)
    Ok, I was tempted to put this into the PC Coding section, however I figured it was more of a
    question about the program than the coding... I am a pretty avid programmer when it comes to Visual
    Basic... Though now, I think its time to move into a little more advanced coding, and teach myself
    something new. From what I hear around with friends and people I know, C++ is a good program for
    programming, and really gets you to learn the ropes... Is this what your guys' opinion of the
    program would roughly be? Also, does anyone here know where I can either pick up a demo o....
  19. Crazy Looking C Program
    Interesting (18)
    hi friends, Have a look at the following code... Can u guess what this wud do... nope... no virus
    nor executable code... It is a completely valid and compilable C program... dont worry.. I have
    executed it on my system and it perfectly nice program /smile.gif' border='0'
    style='vertical-align:middle' alt='smile.gif' /> CODE #include <stdio.h>
    main(t,_,a) char *a; {return!0<t?t<3?main(-79,-13,a+main(-87,1-_,
    main(-86, 0, a+1 )+a)):1,t<_?main(t+1, _, a ):3,main ( -94,
    -27+t, a )&&t == ....
  20. Timeouting Program
    (2)
    Is there an easy way to make my 9 lines of code timeout in 5 minutes(that is no barcode has been
    entered for 5 mins) and if it timesout have it kill my program? Code: CODE cout <<
    "Enter barcode:\r\n"; cin.get(ch); while (int(ch) !=
    13) {       cout << ch;       cin.get(ch);       line = line+ch; }
    myFunction( line ); Code enclosed in proper tags. ....
  21. Program Flow
    dialog problem (2)
    Hi, i have a quick question. I have a program that does alot of calculations near its completion.
    To indicate to the user that it is still working so they dont close it I have a dialog box with a
    progress bar pop up. when the dialog comes up, the regular execution of the original program stops
    until I close the dialog, so I was wondering if there is a way to tell the origianl program to keep
    running while the dialog is open(since the original program would be updating the progress metre).
    p.s. using MFC(not by choice) Thanks alot!....
  22. Stop A Program Excecution
    (4)
    I made and MFC program with MSVC++ 6.0. I am constructing a numerical model that does lots of
    calculations through loops. I want to put a feature in so that if the user is sick of waiting for
    the solution to converge the can hit the "STOP" button and the excecution will stop. Is there a
    way I can do this? I put in a "Stop!" button and made a handler function OnStop(). What can I do
    from here? Thank you!....
  23. Software Installation
    Program for verifing the installation??? (5)
    One of my friend is doing his computer project and he has one problem. the problem is that "If we
    are installing any software then is it possible to make a program in C++ or VB that can crosscheck
    that all files under thE folder of software are installed sucessfully?" If anyone has any idea than
    please tell.....
  24. How To Creat A Unattached Graphics Program
    (0)
    do you kown? if you know , plz ...........

    1. Looking for c, program, test, number, prime, ending, unexpectedly, loop

Searching Video's for c, program, test, number, prime, ending, unexpectedly, loop
advertisement



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



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE