Answer 1:
1 #include <iostream> 2 3 int IsPrime(int number); 4 5 int IsPrime(int number) 6 { 7 if (number <= 1) return 0; // zero and one are not prime 8 int i; 9 for (i=2; i*i<=number; i++) 10 { 11 if (number % i == 0) return 0; 12 } 13 return 1; 14 } 15 16 int main() 17 { 18 int x; 19 std::cin>>x; 20 if(IsPrime(x)) 21 std::cout<<"This number is prime"; 22 else 23 std::cout<<"This number is not prime"; 24 }
Answer 2:
2.1
1)All intergers can be expressed as 2k-1, 2k,where 2 divides 2k;
.........
1 int IsPrime(int number) 2 { 3 if (number <= 1) 4 return 0; // zero and one are not prime 5 else if (number == 2) 6 return 1; // two is prime 7 else 8 { 9 int i; 10 for(i=3;i*i<=number;i+=2) 11 { 12 if(number % i == 0) 13 return 0; 14 } 15 return 1; 16 } 17 }
2.2
1) All intergers can be expressed as 6k-2, 6k-1, 6k, 6k+1, 6k+2, 6k+3,where 2 divides 6k, 6k+2, 6k+4; and 3 divides 6k+3;
2) A nonprime number will be a product of prime numbers;
1 int IsPrime(int number) 2 { 3 if (number <= 1) 4 return 0; // zero and one are not prime 5 else if (number <= 3 && number > 1) 6 return 1; // two and three are prime 7 else if (number%2==0 || number%3==0) 8 return 0; // check if number is divisible by 2 or three 9 else 10 { 11 int i; 12 for(int i=5;i*i<=number;i+=6) 13 { 14 //a nonprime number will be a product of prime numbers;
15 //5,7,11,13,17,19,23(25),29,31,(35),37,41,43,47,(49) 16 if((number % i == 0 || number%(i + 2) == 0)) 17 return 0; 18 } 19 return 1; 20 } 21 }
Answer 3:
1 #include <vector> 2 int IsPrime(int number) 3 { 4 if (number <= 1) 5 return 0; 6 else 7 { 8 std::vector<bool> arrayprime; 9 for (int i = 0; i <= number; i++) 10 arrayprime.push_back(true); 11 for (int i = 2; i <= number; i++) 12 { 13 //This is the Sieve of Eratosthenes problem,see 14 //https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 15 /*if IsPrime(i) //the IsPrime() reduces the number of cycles 16 { 17 for (int j = i + i; j <= number; j += i) 18 { 19 arrayprime[j] = false; 20 } 21 }*/ 22 for (int j = i + i; j <= number; j += i) 23 { 24 arrayprime[j] = false; 25 } 26 } 27 return arrayprime[number]; 28 } 29 }
suppose:number equals to 8
first loop: 0 1 2 3 4 5 6 7 8 second loop: 0 1 2 3 4 5 6 7 8 third loop:0 1 2 3 4 5 6 7 8 fourth loop: 0 1 2 3 4 5 6 7 8
value: 1 1 1 1 0 1 1 1 0 1 1 1 1 0 1 0 1 0 1 1 1 1 0 1 0 1 0 1 1 1 1 0 1 0 1 0
Reference: 1) https://stackoverflow.com/questions/1538644/c-determine-if-a-number-is-prime#
2) https://www.cnblogs.com/xiehongfeng100/p/4332998.html#autoid-0-4-0
3) https://wenku.baidu.com/view/4855d0c450e2524de5187e6c.html