Get the App
SLTechnology News&Howtos  ›  Development  › 

How to find Primes in C language

Shulou Source: shulou.com Published: 2022-06-01 06:30:35 10月02日 Update

This article mainly explains "how to find primes in C language". The content of the explanation is simple and clear, and it is easy to learn and understand. Let's follow the editor's train of thought to study and learn how to find primes in C language.

Preface

Prime numbers are also called prime numbers. The so-called prime number is a number that is not divisible by any integer except 1 and itself. For example, 17 is a prime number, because it is not divisible by any integer from 2 to 16.

Idea 1): therefore, to judge whether an integer m is a prime or not, we only need to divide m by every integer between 2 and m Mui 1. If it is not divisible, then m is a prime.

Idea 2): the judgment method can also be simplified. M does not have to be removed by every integer between 2 and m Mel 1, just by every integer between 2 and 2. If m is not divisible by any integer between 2, m must be a prime. For example, to determine whether 17 is a prime or not, as long as 17 is divided by every integer between 2 and 4, since it is not divisible, it can be determined that 17 is a prime.

Reason: because if m is divisible by any integer between 2 ~ m color 1, one of its two factors must be less than or equal to, and the other greater than or equal to. For example, 16 is divisible by 2, 4, 8, 16 is less than 4, 8 is greater than 4, 16 is 4, 4 is 4, and 4 = √ 16, so it is only necessary to determine whether there is a factor between 2 and 4.

Idea 1 implementation: # include int main () {int n; printf ("Please enter an integer between 1 and 100:\ n"); scanf ("% d", & n); int m = 0; for (int I = 2; I < n; iTunes +) {if (n% I = = 0) {masks + }} if (m = = 0) {printf ("% d is a prime\ n", n);} else {printf ("% d is not a prime\ n", n);} return 0;} idea 2 implementation: # include # include int main () {int n; printf ("Please enter an integer between 1 and 100:\ n"); scanf ("% d", & n) Int I = 0; int Q = sqrt (n); for (I = 2; I Q) {printf ("% d is a prime\ n", n);} else {printf ("% d is not a prime\ n", n);} return 0;} "C and pointer" 4.14-2:

Print all prime numbers between 1 and 100:

# include int main () {int num, divisor; printf ("1,2"); for (num = 3; num = num) {printf (",% d", num);}} printf ("\ n"); return 0;}

Results:

1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97

Add: four methods for judging primes: example # include#include// method 1: judging one by one from 1 int n; bool isPrimel_1 (int n) {for (int item2witi)

Tags: Prime integer inter method idea language just need factor odd that is any learning input maximum number content result if prime even. Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Xiaomi MySQL MariaDB Shulou Tech Info