current position:Home>On the problem of C language: prime is a number that has no other factors except 1 and itself

On the problem of C language: prime is a number that has no other factors except 1 and itself

2022-02-02 20:17:40 CSDN Q & A

Give a number , Judge whether it is a prime number .
Prime numbers are all except 1
A number that has no other factor than itself




Refer to the answer 1:
int isPrime(int n) {              // (1)    int i, sqrtn = sqrt(n + 1e-6);    if(n <= 1) {        return 0;                 // (2)    }    for(i = 2; i <= sqrtn; ++i) {        if(n % i == 0) {          // (3)            return 0;        }    }    return 1;                     // (4)}

( 1 ) (1)(1) Define a function , Function passed in parameters n, If n Return for prime 1; Otherwise return to 0;
( 2 ) (2)(2) When n <= 1 when , It must not be a prime , Go straight back to 0;
( 3 ) (3)(3) If you find a number , yes n nn Factor of , And it's not worth it 1, be n It must not be a prime , return 0;
( 4 ) (4)(4) Division not found n nn and 1 11 Other factors , It means it's a prime number and hasn't run away , Go straight back to 1;




Refer to the answer 2:



Refer to the answer 3:
isPrime(int n){    if(n == 1) return 0;    int i;    for(i = 2;i*i <= n;i++){ 
            if(n % i == 0) return 0;    }    return 1;}



Refer to the answer 4:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202022017385321.html

Random recommended