Home > Back-end >  The purple book chapter iv function and recursive
The purple book chapter iv function and recursive

Time:11-04

Function parameters for structural form
Struct Point {double x, y; };
Double dist (struct Point a, struct Point b) {
Return hypot (a.x - b.x a.y - b.y);
}
To avoid the struct writing
Typedef struct {double x, y; } Point;
Double dist (Point a to Point b) {
Return hypot (a.x - b.x a.y - b.y);
}
Prime Numbers determine
Int is_prime (int n) {
If (n<=1) return 0;
Int m=floor (SQRT (n) + 0.5);
for(int i=2; i<=m; I++) {
If I (n %==0) return 0;

}
return 1;
}

CodePudding user response:

Prime Numbers determine
Description
Prime Numbers is also called the prime Numbers, and its definition is: can only be divided exactly by 1 and itself, is greater than 1 integer called prime,
Thinking
Based on the definition of prime Numbers, n<=1 case directly to; If n> 1, if you say you use a for loop from 2 to n scan it again, that is right, but you can only scan from 2 to SQRT (n) is ok, because n/x=y and n/y=x is equal to the repeated judgment, algorithm efficiency is greatly reduced, and I see him on Liu Rujia teacher's book is such a calculation on the boundary: int m=floor (SQRT (n) + 0.5), and he says this is to avoid floating point error, then I carefully thought for a moment, if when n particularly big, may be due to the error precision, this should be an integer into a x. 9999 or x. 9998 and so on, so it is important to pay special attention to,
Liu Rujia teacher code below

Int is_prime (int n)
{
If (n<=1) return 0;
Int m=floor (SQRT (n) + 0.5);
for(int i=2; i<=m; I++)
If I (n %==0) return 0;
return 1;
}
Ps: on the floor is a integral function, for example, x=3.14, floor (x)=3; Y=9.99999, floor (y)=9,

CodePudding user response:

From https://www.cnblogs.com/flyawayl/p/8305615.html
  • Related