zoukankan      html  css  js  c++  java
  • C语言复习---判断素数

    一般

    int main01()
    {
        int a, n_sqrt, flag=1;
        scanf("%d", &a);
        n_sqrt = sqrt(a);
        for (int i = 2; i <= n_sqrt; i++)
            if (a%i == 0)
            {
                flag = 0;
                break;
            }
                
        if (flag)
            printf("%d is
    ", a);
        else
            printf("%d not
    ", a);
    
        system("pause");
        return 0;
    }
    
    int main()
    {
        int a, n_sqrt,i;
        scanf("%d", &a);
        n_sqrt = sqrt(a);
        for (i = 2; i <= n_sqrt; i++)
            if (a%i == 0)
                break;
    
        if (i>n_sqrt)
            printf("%d is
    ", a);
        else
            printf("%d not
    ", a);
    
        system("pause");
        return 0;
    }

    高效率

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    //... 6x-1,6x,6x+1,6x+2,6x+3,6x+4,6x+5,6(x+1),6(x+1)+1 ...
    //可以看出6x,6x+2,6x+3,6x+4都是因数
    //6x-1,6x+1中有一定几率是素数   例如:23 25
    int isPri(n)
    {
        float n_sqrt;
        int i = 0;
    
        //对小于5的进行判断
        if (n == 2 || n == 3)
        {
            return 1;
        }
    
        //筛选不必要的
        if (n % 6 != 5 && n % 6 != 1)
        {
            return 0;
        }
    
        //进行数据筛选
        n_sqrt = floor(sqrt((float)n));    //floor向下取整
        for (i = 5; i < n_sqrt;i+=6)    //以6为步长
        {
            if (n%i == 0 || n % (i + 2) == 0)    //判断i和i+2就是6n+5和6n+7(n从0开始)可以看做6m-1,6m+1(m从1开始)
                return 0;
        }
    
        return 1;
    }
    
    
    int main()
    {
        int i = 0;
        for (; i < 200;i++)
        {
            if (isPri(i)==1)
            {
                printf("%d ", i);
            }
        }
    
        system("pause");
        return 0;
    }
  • 相关阅读:
    Go interface{}、类型断言
    相关资料
    php实践
    安装zookeeper
    对象池化,对象池
    java getResourcesAsStream()如何获取WEB-INF下的文件流
    android--SDK Manager下载Connection to http://dl-ssl.google.com refused
    Intellij idea 切换SVN路径
    Intellij Idea @Autowired取消提示
    恢复文件默认打开方式
  • 原文地址:https://www.cnblogs.com/ssyfj/p/9376624.html
Copyright © 2011-2022 走看看