0

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.

Edited by Valiantangel: correction

4
Contributors
8
Replies
10
Views
4 Years
Discussion Span
Last Post by pyTony
0

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?

0

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;

Edited by Valiantangel: Correction

1

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.

Edited by wen_cai: Extra comments

0

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:)

Edited by Valiantangel: correction

0

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;
>                 }
>             }
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.