zoukankan      html  css  js  c++  java
  • C语言之判断一个数是否为素数

    #include "stdio.h"
    #include"time.h"
    #include"math.h"
    
    int isPrimeNumber(int number) { //判断是否为素数
        float sqrtOfNum = sqrt((double) number);
        for (int j = 2; j <= sqrtOfNum; j++) //从2到number的算术平方根迭代
            if (number / j * j == number) //判断j是否为number的因数
                return 0;
        return 1;
    }
    
    void printNum(int number) { //打印出 <= number的所有质数
        int j = 0;
        for (int i = 2; i <= number; i++)
            if (isPrimeNumber(i) == 1) {
                printf("%-10d", i);
                j++;
                if (j % 10 == 0) //每隔十个数字换行
                    printf("
    ");
            }
    }
    
    int main() {
        long start = time(NULL);
        printf("%d
    ", isPrimeNumber(29));
        printNum(100);
        printf("
    ");
        long end = time(NULL);
        printf("Time spent: %d", end - start);
    }

    运行结果:

    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        
    Time spent: 0
    苟利国家生死以, 岂因祸福避趋之
  • 相关阅读:
    ZOJ 3795 Grouping
    ZOJ 3791 An Easy Game
    ZOJ 3790 Consecutive Blocks
    POJ 1451 T9
    POJ 1141 Brackets Sequence
    POJ 2411 Mondriaan's Dream
    POJ 2513 Colored Sticks
    Eclipse 快捷键大全
    C# lock关键字(多线程)
    C# 内部类
  • 原文地址:https://www.cnblogs.com/chintsai/p/10117053.html
Copyright © 2011-2022 走看看