CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 13 of 13
  1. #1
    Join Date
    Feb 2013
    Posts
    4

    Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Calculate the first N emirp (prime, spelled backwards) numbers, where N is a positive number that the
    user provides as input. An Emirp is a prime number whose reversal is also a prime. For example, 17 is a
    prime and 71 is a prime, so 17 and 71 are emirps. Write a program that prints out the first N emirps,
    five on each line.
    For example:

    For this assignment, you are required to make use of 2 functions (which you must write).
    bool isPrime(int value); // Returns true if value is a prime number.
    int reverse (int value); // Returns the reverse of the value (i.e. if value is 35, returns 53).

    You should follow a top-down design, using these functions in conjunction with logic in main, to perform
    the computation of N emirps and print them out according to the screenshot above. The general outline
    for main would be as follows:

    Step 1: Ask user for positive number (input validation)
    Step 2: Initialize a variable Test to 2
    Step 3: While # emirps found is less than the input:
    Call isPrime with Test, and call it again with
    reverse(Test). If both are prime, print and increment
    number of emirps found.
    Test++

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    So, what parts of this task have you already made?
    What problems do you have and with what?

    Besides, have a look at his FAQ
    Victor Nijegorodov

  3. #3
    Join Date
    Feb 2013
    Posts
    4

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    #include <iostream>
    using namespace std;
    bool isPrime(int value); //Prototyle for "prime number function"
    int reverse (int value2); //Prototype for "emirp function"

    int main()
    {
    //Ask the user for a positive number

    cout << "Please enter a positive number: ";
    int n;
    cin >> n;
    //Reject negative value input

    if ( n < 1)
    {
    cout << "INVALID NUMBER \n";
    }
    else
    {
    //Calculate all emirps up to 'n'.

    int test = 0;
    int number = 2;
    while (test < n)
    {
    int RevNum = reverse(number);

    if (isPrime(number) &&RevNum)
    {
    cout << "\n" << RevNum << "\t\t\t";
    test++;
    }
    else
    {
    test++;
    }
    }
    }
    system("pause");

    return 0;
    }

    int reverse(int value2)
    {
    //reverse the number
    value2*=10;
    value2 = value2 %10;
    value2/=10;
    //same procedure as prime function

    int divisor2 = 1;
    int count2 = 0;
    int emirp = 0;
    if (value2 % divisor2 == 0)
    {
    count2++;
    ++divisor2;
    }
    if (count2 == 2)
    {
    int emirp = value2;
    }
    return emirp;
    }

    bool isPrime(int value)
    {
    //If value is prime, the remainder (count) will be zero twice--for 1 and itself.

    int divisor = 1;
    int count = 0;
    int prime = 0;
    if (value % divisor == 0)
    {
    count++;
    ++divisor;
    }
    if (count == 2)
    {
    return true;
    }
    else
    {
    return false;
    }
    }

    After I enter the 'n; value, the program just ends and I don't see the numbers. I have tried a few other things, and the numbers were either all 0s or all 2s. Sorry if it seemed like I was trying to cheat. I was just frustrated after working on this for so many hours. I'd appreciate any feedback and advice on where I went wrong to get the incorrect results. Thank you for your time.

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    First, you have to use Code tags while posting code snippets. Otherwise your code is unreadable! See Announcement: Before you post....
    Second, you have to debug your code to see where, how and why something goes wrong. Set a break point at the beginning of the main(), then press F5 to start debugging, then F10 for each next step... and see the values of your variables in the watch window(s)...
    Victor Nijegorodov

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Quote Originally Posted by ciscoqueen90x View Post
    I was just frustrated after working on this for so many hours.
    Didn't the "Debug" menu option in Visual C++ give you an idea to try it? You would have saved yourself hours of time. All you had to do is hit F10 after your program was built, and just keep hitting F10 to get the idea of what the debugger does for you.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; February 8th, 2013 at 05:18 AM.

  6. #6
    Join Date
    Feb 2013
    Posts
    4

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    What if there are no values listed in the watch window? Sometimes that happens to me.

  7. #7
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Quote Originally Posted by ciscoqueen90x View Post
    What if there are no values listed in the watch window? Sometimes that happens to me.
    1) You have to add the items to the watch window. They aren't put there automatically.

    2) Make sure you're compiling a "Debug" version, not a "Release" version (actually, an unoptimized version, regardless of whether it is Debug or Release).

    Regards,

    Paul McKenzie

  8. #8
    Join Date
    Feb 2013
    Posts
    4

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Wow, I did not know that. Thank you, I will have to try that.

  9. #9
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    If the code provided here is the result of you working on it for about 8 hours are you sure programming is for you? There are so many things not right with this program I don't know where to start. But firstly you need to think about the definition of a prime "A Prime Number can be divided evenly only by 1, or itself". So if a number(n) can be divided by any number between 2 and n-1 inclusive then it is not prime. To test if a number is prime you need a loop. You can't just do it with a couple of if statements! I suggest that you start by getting the isPrime function to work properly first then get reverse function to be correct. Once you have these functions performing as they should then the main program should be easy.

  10. #10
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Quote Originally Posted by Paul McKenzie View Post
    1) You have to add the items to the watch window. They aren't put there automatically.
    Alternatively, use the Locals or Auto windows. They know by themselves which variables to display so there's no need for you to tell them. (The difference between the two is the criteria by which they choose the variables to display.) I almost never use the Watch window in favor of these two, and find that quite convenient.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  11. #11
    Join Date
    May 2002
    Posts
    1,798

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Take a look at the attached console program I wrote. Let me know if you have questions. I did this because it's an interesting problem.
    mpliam

  12. #12
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Humm.. It's not very efficient. As prime numbers cannot be even, why test every even number in the loop? You can just test if divisible by 2 at the beginning and then start the loop at 3 and increment by 2. Also, there's no need to test all numbers up to the one being tested. As a number squared is divisible by the number, the loop test can stop at the square root of the tested number.

    Code:
    //A Prime Number can be divided evenly only by 1, or itself
    //So if a number(n) can be divided by any number between 2 and n-1 inclusive then it is not prime
    //An even number is never prime
    bool IsPrime(int num)
    {
    	//numbers 1 and 2 are defined as prime
    	if ((num == 1) || (num == 2))
    		return true;
    
    	//Even numbers are never prime
    	if ((num % 2) == 0)
    		return false;
    
    const int limit = (const int)sqrt((double)num);
    
    	//Need only consider odd numbers before sqrt
    	for (int i = 3; i <= limit; i += 2)
    		if ((num % i) == 0)
    			return false; // not prime
    
    	return true;
    }
    Why not use the IsPrime function in GetPrimes rather than repeat the same code twice? Also passing the vector by reference is more efficient than returning a vector.
    Code:
    typedef vector<int> PRIMES;
    
    //Put the first N prime numbers into a vector
    void GetPrimes(PRIMES& vp, int no)
    {
    int	prime = 3,	//Start primes at 3
    	fnd = 0;	//Number found
    
    	while (fnd <= no) {
    		if (IsPrime(prime)) {
    			vp.push_back(prime);	//Save prime
    			fnd++;
    		}
    		prime +=2;	//Only odd numbers
    	}
    	return;
    }
    Again, with ReverseInteger, there is a much more efficient method without the overhead of converting to and from a string

    Code:
    //Reverse an integer
    int ReverseInteger(int no)
    {
    int rnum = 0;
    
    	while (no) {
    		rnum = rnum * 10 + (no % 10);
    		no /= 10;
    	}
    
    	return rnum;
    }

    So the main program now looks like

    Code:
    int main()
    {
    int	num,
    	prime,
    	rprime;
    
    PRIMES	Vp;
    
    	cout << "Enter number of primes to check for emirp status: ";
    	cin >> num;
    
    	GetPrimes(Vp, num);
    
    const size_t noprimes = Vp.size();
    
    	for (size_t i = 0; i < noprimes; i++) {
    		prime = Vp[i]; 
    		rprime = ReverseInteger(prime);
    		cout << prime << " is prime ";
    		if (IsPrime(rprime)) {
    			cout << "and " << rprime << " is prime so " << prime << " is emirp " << endl;
    		} else {
    			cout << "but " << rprime << " is not prime so " << prime << " is not emirp " << endl;
    		}
    	}
    
    	return 0;
    }

  13. #13
    Join Date
    May 2002
    Posts
    1,798

    Re: Worked on this C++ function assignment for about 8 hours!!! Please post solution.

    Nice. But I think my approach is more instructive for a student because it's so modular. Your methods, while more elegant, assume some prior knowledge of number theory beyond just knowing what a prime number is. And your method reversing a number, while quite impressive, again requires some sophisticated knowlege of number theory. I suspect you're something of a mathematician ? Recall, this is supposed to be a programming lesson. As Paul and others have stated, the first step in solving a programming problem is to break the problem down into segments, then attack each segment individually, then put them all together, rather than trying to do the whole thing at once. At least, this works better for me. Mozart claimed an entire symphony would come into his head all at once. But I'm no genius, so the piece-wise approach, while not quite as elegant, works for me.

    Please don't misunderstand me. I like your code very much.
    Last edited by Mike Pliam; February 15th, 2013 at 10:57 AM.
    mpliam

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured