Thread: C program for prime numbers

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    11

    C program for prime numbers

    I am new in c programming. I want to make a program in which when I enter a number the program should tell me whether it is prime or not. I have found various programs on internet but they are all difficult to me. I have logic in my mind "Whenever I enter a number",
    STEP 1: The program should divide it by "2" if the result is a natural number it should declare that it's not prime number.
    STEP 2: Else program should divide entered number by "3" if the result is a natural number it should declare that it's not prime number.
    The program should continue to divide by 4,5,6,7,8 and 9. If (dividing from 2 to 9) the result is not a natural number in every case the program must declare that "number is prime". I have made very rough program (with wrong results) and I think I should not paste it here so that no body makes me a joke.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Post your program.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by arslan20 View Post
    The program should divide it by "2" if the result is a natural number it should declare that it's not prime number.
    Using integer math, it would be easier to get the remainder of the number divided by 2 (for example, n % 2), and if the remainder is zero, the number is not prime.

  4. #4
    Registered User
    Join Date
    May 2012
    Posts
    505
    This is an example of problem which is straightforwards, but not absolutely trivial, to solve for small numbers, and a mathematical research problem to solve quickly for large numbers.
    The first thing to do is to write a completely naive function, with no attempt at optimisation whatsoever, that tells you whether a number has any factors of 2 or greater.
    Then think 1), what is the greatest factor possible, and how can I calculate it efficiently (there's a function which will do this for you, which is a bit of a cheat), 2) do I need to try every number as a factor, or are there some I can eliminate, how much speed up will I get by eliminating some tests?).
    Then run lots and lots of tests on random numbers, calling your naive function and the efficient one. Do they always give the same results?
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    11
    Here is my rough program
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
        int a,b,c,d,e,f,g,h,i;
        printf("Enter a number");
        scanf("%d",&a);
        b=a%2;
        if (b==0)
        printf("number is not prime");
        else
        c=a%3;
        if (c==0)
        printf("number is not prime");
        else
        d=a%4;
        if (d==0)
        printf("number is not prime");
        else
        e=a%5;
        if (e==0)
        printf("number is not prime");
        else
        f=a%6;
        if (f==0)
        printf("number is not prime");
        else
        g=a%7;
        if (g==0)
        printf("number is not prime");
        else
        h=a%8;
        if (h==0)
        printf("number is not prime");
        else
        i=a%9;
        if (i==0)
        printf("number is not prime");
        else
        printf("number is prime");
        getch();
    }

  6. #6
    Registered User
    Join Date
    Mar 2013
    Posts
    11
    but this program yields correct result for prime numbers greater than 10 and wrong for each number

  7. #7
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Is your variables the alphabet or am I mistaken? Probably the second, but should name your variables with names that represent what they mean and their usage.
    For example, if I want to calculate the sum of 0, 1 ,2 and 3, I would name the variable that accumulates the result as sum and not as bla.
    First think the mathematical method. When does a number is prime?
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  8. #8
    Registered User
    Join Date
    Mar 2010
    Posts
    583
    If you take for example an input of 5... your program will divide 5 by 5 and get remainder 0 so conclude it is not a prime.

    A prime is a number with exactly 2 divisors -- 1 and itself. So you need to make sure that you check for that -- all numbers divide by themselves - it doesn't make them non prime.

    You program also currently doesn't correctly detect whether numbers are primes or not above a certain value. For example, it'd report 1159 as a prime, but 1159 is 19*61. To test larger primes, you'll probably want to learn how to use a loop. It'll do exactly what you're already done but without you having to write it all out.

    One step at a time though. For now, I think your program will correctly identify primes up to around 100. You could change the prompt to say "enter a number between 1 and 100" and complain if the user puts something out of bounds in.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You have a number, and you want to test if it's prime or not, using trial by division method.

    OK.

    So you described the algorithm in an earlier post, and that sounded very good.

    This code, is not that algorithm, however.

    Get the number to be tested from the user. Call it int number.
    Test that number, from 2 up to number - 1, using division and checking whether there is a remainder left over, after the division is made. (There is a nice speed up but accept this for now. Optimize it later, after it's accurate.

    That division and checking the remainder, is what the mod operator in C does: %, so that's helpful, but the most helpful thing is to make your tests in a loop, instead of in lots of repetitions, like you have above.

    A for loop would be very appropriate


    How would that go?
    Code:
    for(i=2; i <    //fill in the rest of this

  10. #10
    Registered User
    Join Date
    May 2012
    Posts
    505
    Quote Originally Posted by arslan20 View Post
    Here is my rough program
    Code:
    #include<stdio.h>
    #include<conio.h>
    int main(void)
    {
        int a,b,c,d,e,f,g,h,i;
        printf("Enter a number");
        scanf("%d",&a);
        b=a%2;
        if (b==0)
        printf("number is not prime");
        else
        c=a%3;
        if (c==0)
        printf("number is not prime");
        else
        d=a%4;
        if (d==0)
        printf("number is not prime");
        else
        e=a%5;
        if (e==0)
        printf("number is not prime");
        else
        f=a%6;
        if (f==0)
        printf("number is not prime");
        else
        g=a%7;
        if (g==0)
        printf("number is not prime");
        else
        h=a%8;
        if (h==0)
        printf("number is not prime");
        else
        i=a%9;
        if (i==0)
        printf("number is not prime");
        else
        printf("number is prime");
        getch();
    }
    Ok, I see the problem.

    Programming variables are not the same as algebra unknowns.
    In algebra if we say b = a % 2 and c = a % 3, then b and c must retain those values for the rest of the calculation. So you need
    a new symbol for each value.
    In programming we often say things like x = x +1. Which means
    take x, add one to it, and set x to the new value. It's virtually
    essential to do this, because programming is all about loops, doing the same calculation over and over again with slightly different values.
    You only need one or two variables to write your program.
    I'm the author of MiniBasic: How to write a script interpreter and Basic Algorithms
    Visit my website for lots of associated C programming resources.
    https://github.com/MalcolmMcLean


  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    This code is unacceptable to anyone who knows how to program. You must use a loop here.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Here is a modified version of the program, still not using loops, and yes it's using goto's but at least it shows the basic logic to determine if a number is prime. It would be better to create a program to generate an array of prime numbers up to some value "n", using a loop.

    Code:
    #include<stdio.h>
    #include<conio.h>
    
    int main()
    {
        int a;
        printf("Enter a number: ");
        scanf("%d",&a);
        if ((a%2)==0 && a != 2)
            goto notprime;
        if ((a%3)==0 && a != 3)
            goto notprime;
        if ((a%5)==0 && a != 5)
            goto notprime;
        if ((a%7)==0 && a != 7)
            goto notprime;
        if ((a%11)==0 && a != 11)
            goto notprime;
    
        printf("number is prime");
        goto exit0;
    
    notprime:
        printf("number is not prime");
    
    exit0:
        getch();
    }
    Last edited by rcgldr; 05-18-2013 at 06:57 PM.

  13. #13
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Gack! I thought my cat had a furball in his throat. I realise now that it is code from this thread.

    The OP may want to look up "Sieve of Eratosthenes". It is an approach for searching for primes.

    If that is too hard, you might want to also think about how to simplify your approach. For example, I bet that there is no number divisible by 6 that is not divisible also by 2 and by 3. So if a value is not divisible by 2 it cannot be divisible by 6.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Welcome to the forum, arslan20!

    Don't worry that your code is "not acceptable" - because no real beginner's code is acceptable. We just aren't born with the knowledge and skill of C programming already inside. By definition, every beginner's code is unacceptable, until they've mastered the basics, at least.

    For now, stick with the "Trial by Division" method of finding out whether a number is prime or not. That is exactly what you posted that you want to do.

    Take a simple example, and work it through, (may take several times, before the "light" of understanding turns on), but study the patterns you see as you do it.

    Say I ask you if the number 9 is prime. You could see it being solved by a series of steps, like this:
    Code:
    // if the remainder of 9/2 is 0
    if(9 % 2 == 0) 
       9 is not prime
    
    // if the remainder of 9/3 is 0
    if(9 % 3 == 0)
        9 is not prime
    Now the challenge is to put the two tests shown above, into a loop, because programming uses loops VERY heavily indeed. You could use either a for loop, or a while loop. A while loop, in pseudo code might look like:
    Code:
    int i = 2;
    int n = 9;
    while(n % i not equal zero, and i is less than n )
       increment i
    Study that logic, and start working out how it can be done, using a loop. Either a for loop, or a while loop, is OK. Whichever loop makes more sense to you, is fine.

    Later, we'll show you how this can be done in much less time, but for now, concentrate on getting a program in loop (and you, thinking in loops), and getting an accurate program.
    Last edited by Adak; 05-18-2013 at 07:53 PM.

  15. #15
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    The best place to start is to work out how to determine if a number is a prime

    There are a lot of different ways of doing it, but a good way to start is to use real examples

    Is the number 15 a prime number? is the number 17 a prime number?
    What did you do to work these out?

    Can 15 be divided by 2? No
    Can 15 be divided by 3? Yes -> Not a prime

    Can 17 be divided by 2? No
    Can 17 be divided by 3? No
    Can 17 be divided by 4? No
    ... What number would you stop checking?

    It is SO important to be formilar with what the background of what your program needs to achieve.
    A lot of problems out there have shortcuts and faster algorithms, and if you don't find them, you are making
    a slow algorithm.
    Have a look at this page for the answer of what number to stop at: Prime number - Wikipedia, the free encyclopedia

    Can this be a loop?
    i=2
    Can 17 be divided by 'i'? No
    i = i + 1
    Can 17 be divided by 'i'? No
    i = i + 1
    Can 17 be divided by 'i'? No
    i = i + 1
    ...

    What number would you stop 'i' at and say that there are no divisors? If there are no divisors, it must be a prime.
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-16-2012, 02:07 AM
  2. non prime numbers or composite numbers program.help plz!
    By danishzaidi in forum C Programming
    Replies: 10
    Last Post: 11-15-2011, 11:10 AM
  3. Prime numbers program
    By Prestige in forum C Programming
    Replies: 3
    Last Post: 10-16-2010, 01:57 PM
  4. /i need help in C- program for prime numbers plzZzZ
    By linda in forum C Programming
    Replies: 13
    Last Post: 03-04-2008, 06:44 AM
  5. C Program for Prime Numbers
    By mmuhlenb in forum C Programming
    Replies: 12
    Last Post: 02-19-2003, 04:55 AM