CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7
  1. #1
    Join Date
    Jul 2010
    Posts
    75

    Question Prime Number Test

    Hi
    Got 2 errors
    the program should let me enter number and check whether its a prime or not



    Error 1 error C2668: 'sqrt' : ambiguous call to overloaded function c:\users\hani\test4\test4\code.cpp 15

    Error 2 fatal error C1903: unable to recover from previous error(s); stopping compilation c:\users\hani\test4\test4\code.cpp 15

    PHP Code:

    # include <iostream>
    # include <cmath>
    using namespace std;

    int main () { 

        
    int n;
        
    int i;
        
    int is_prime=true;

        
    cout << " enter a number ";
        
    cin >>n;

        
    2;
        while ( 
    <= sqrt(n)) {
            if ( 
    ==0)
                
    is_prime false;
            
    i++;
        }

        if ( 
    is_prime )
            
    cout << " the number is prime "<<endl;
        else
            
    cout << " is not prime number "<<endl;

    system ("PAUSE");
    return 
    0;



  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: Prime Number Test

    You are taking the sqrt of an int variable. The compiler does not know which overload
    of sqrt to use (float ? double ?). You need to explicitly tell the compiler what to use:

    Code:
        while ( i <= sqrt( static_cast<double>(n) ) ) {

  3. #3
    Join Date
    Jul 2010
    Posts
    75

    Re: Prime Number Test

    Thanks Philip

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Prime Number Test

    As an aside, a very easy way to convert an int to a double is to add 0.0, for instance
    Code:
    while ( i <= sqrt( n + 0.0 ) ) {

  5. #5
    Join Date
    Jul 2010
    Posts
    75

    Re: Prime Number Test

    checked it lindley nice work

  6. #6
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,244

    Re: Prime Number Test

    [ Moved thread ]
    Ovidiu
    "When in Rome, do as Romans do."
    My latest articles: https://codexpertro.wordpress.com/

  7. #7
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: Prime Number Test

    Code:
    int is_prime=true;
    should be
    Code:
    bool is_prime=true;
    to avoid implicit conversions.

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