编写一个程序,将小于n的所有质数找出来。

来源:互联网 发布:linux报错e45 编辑:程序博客网 时间:2024/05/22 06:24

c#实现如下:http://www.nowcoder.com/profile/454285/test/3057105/36326#summary

using System;using System.Collections.Generic;namespace ceshi{    class taotao    {        static List<int> array = new List<int>();        static void Main(string[] args)        {            int n = Convert.ToInt32(Console.ReadLine());            Console.WriteLine("小于{0}的所有指数如下:", n);            Prime(n);            foreach (var item in array)            {                Console.WriteLine(item);            }        }        static void Prime(int n)        {            for(int i = 0; i < n; i++)            {                if (i <= 1) continue;                if (i == 2)                {                    array.Add(i);                    continue;                }                for (int j = 2; j < Math.Sqrt(i) /*&& i % j == 0*/; j++)                {                    if (i % j == 0)                        break;                    array.Add(i);                }            }        }    }}

c++如下:

#include<iostream>//#include <vector>#include <cmath>using namespace std;bool isPrime(int x){if(x <= 1)return false;if(x == 2) return true;for (int i = 2; i <= sqrt((float)x); ++i){if(x % i == 0)return false;}return true;}vector<int> getAllPrimes(int n){vector<int> res;if(n < 2) return res;for(int i = 2; i < n; ++i){if(isPrime(i)){res.push_back(i);}}return res;}void main(){int n;cin>>n;//vector<int> result = getAllPrimes(n);for(int i = 0; i < result.size(); i++){cout<<result[i]<<endl;}system("pause");}



0 0
原创粉丝点击