素数判定c语言acm,素数判断_ACM竞赛_ACM/CSP/ICPC/CCPC/比赛经验/题解/资讯_牛客竞赛OJ_牛客网...

School Method

A simple solution is to iterate through all numbers from 2 to n-1 and for every number check if it divides n. If we find any number that divides, we return false.

Below is the implementation of this method.

// A school method based C++ program to check if a

// number is prime

#include 

using namespace std;

bool isPrime(int n)

{

// Corner case

if (n <= 1)  return false;

// Check from 2 to n-1

for (int i=2; i

if (n%i == 0)

return false;

return true;

}

// Driver Program to test above function

int main()

{

isPrime(11)?  cout <

isPrime(15)?  cout <

return 0;

}

Optimized School Method

We can do following optimizations:

Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.

The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = -1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia)

Below is the implementation of this solution.

// A optimized school method based C++ program to check

// if a number is prime

#include 

using namespace std;

bool isPrime(int n)

{

// Corner cases

if (n <= 1)  return false;

if (n <= 3)  return true;

// This is checked so that we can skip

// middle five numbers in below loop

if (n%2 == 0 || n%3 == 0) return false;

for (int i=5; i*i<=n; i=i+6)

if (n%i == 0 || n%(i+2) == 0)

return false;

return true;

}

// Driver Program to test above function

int main()

{

isPrime(11)?  cout <

isPrime(15)?  cout <

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值