一、如何写一个判断某输入数字是否为素数(即质数)?
简单来说有两种方法:假设从键盘输入一个整数n
【方法一】判断n是否能被2~n-1间的整数除
1 int isPrime(int k) 2 { 3 int j; 4 for ( j=2; j<k; j++ ) 5 { 6 if(k%j==0) // 如果不为素数返回0 7 { 8 return 0; 9 } 10 } 11 return 1; // 反之则返回1 12 }
【方法二】判断n是否能被2~√n间的整数除
1 int isPrime(int k) 2 { 3 int j; 4 for ( j=2; j<=sqrt(k); j++ ) 5 { 6 if(k%j==0) // 如果不为素数返回0 7 { 8 return 0; 9 } 10 } 11 return 1; // 反之则返回1 12 }
import:方法一与方法二中,后者的空间复杂度更小,效率更高,不易出错,亲测,五星good job (๑•̀ㅂ•́)و✧
·············································································Graceful Line···············································································································
计算机小白懵懂求学
敬请批评指正!谢谢!
----yuhaow