Just need some understanding on the various Prime number calculations.Please explain

  1. verify by brute force that a number is evenly divisible only by 1 and itself.(dont implement the Sieve of Eratosthenes algorithm)
  2. writing and running the program with upper limits of n/2 and the square root of n. SUBMIT YOUR SOLUTION USING THE SQUARE ROOT OF N AS THE UPPER LIMIT.

Post your code/pseudocode and explain the point of difficulty/unclarity.

i had a lab similar to this once. post some code and ill be glas to help out

You want an explaination of the Sieve of Eratosthenes algorithm and square root of n upper limit algorithm or the code for both those solutions?

ans to :
1. using brute force to calculate i used:

            if ( num <= 1 ) 
                return false; 
            // calculates through 2 to num to find the prime numbers
            for ( int prime = 2; prime <= num; prime++ )
            {            
                if ( num % prime == 0 ) 
                    return false;
                }

            return true;
            }

2.Not exactly sure but below is my code

for( int prime = 2; prime <= Math.sqrt(n); prime++) {
            if( n % prime == 0 ){
                return false;
            }
        }
        return true;

for ( int prime = 2; prime <= num; prime++ )

Correct me if I am wrong. Your prime must be less than number not less than or equal to number. This is because if prime and number are equal, then it will always return false and will never return true. Also, line 10 of your 1st solution should be outside of the for loop. Else it will only do the check once.

The question did ask for the number to be less than prime.But my question is does it have to be? Cant the number be prime?

This is because if prime and number are equal, then it will always return false and will never return true.

I dont understand what you mean by this.

As for the 11 } outside loop, its a copy and past error:)

Eventually prime and num variable will be equal. Once they are equal, the if statement where the num % prime will be true eventually and will always return false.

>             for ( int prime = 2; prime <= num; prime++ )
>             {            
>                 if ( num % prime == 0 ) 
>                     return false;
>                 }
>             }

Other way to spot this is to see that there is no possibility for the function to return true (or at least not zero) value, so you have also another fix to make.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.