using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace Data
{
//计算n除以从2到根号n最接近的整数,如果都不能整除,n就是质数
//比如101,要计算101除以2,3,4,5直到10,如果都不能整除,就是质数。
class Program
{
static void Main(string[] args)
{
//BitArray数组是有Set和Get方法的键值对(索引,true)or (索引,false)
BitArray bits = new BitArray(25);
BuildSieve(bits);
Console.WriteLine();
while (true)
{
Console.WriteLine("输入一个数字,判断是否是数字?");
string str = Console.ReadLine();
if (bits.Get(Convert.ToInt32(str)))
Console.WriteLine(str + "是素数!");
else
Console.WriteLine(str + "不是素数!");
}
}
static void BuildSieve(BitArray bits)
{
string primes = "";
//先设置让所有的元素都是true
for (int i = 0; i < bits.Count; i++)
bits.Set(i, true);
//求数组长度的平方根
int lastbit = Convert.ToInt32(Math.Sqrt(bits.Count));
for (int i = 2; i < lastbit; i++)
{
if (bits.Get(i))
{
//一定要float不然会溢出的,这样在有小数的情况下可以保证前一位整数可以进入循环
for (int j = 1; j < (float)(bits.Count) / i; j++)
{
//i*1就是本身,所以要排除,这样j++就排除了这些数是所有倍数,如第一个2,i*j然后j++就排除了4,6,8。。。,而j==1的时候取2就不会排除2本身
bits.Set(i * (j==1?2:j), false);
}
}
}
int count = 0;
for (int i = 2; i < bits.Count; i++)
if (bits.Get(i))
{
primes += i.ToString() + " ";
count++;
}
Console.Write(primes);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Diagnostics;
namespace Data
{
//计算n除以从2到根号n最接近的整数,如果都不能整除,n就是质数
//比如101,要计算101除以2,3,4,5直到10,如果都不能整除,就是质数。
class Program
{
static void Main(string[] args)
{
//BitArray数组是有Set和Get方法的键值对(索引,true)or (索引,false)
BitArray bits = new BitArray(25);
BuildSieve(bits);
Console.WriteLine();
while (true)
{
Console.WriteLine("输入一个数字,判断是否是数字?");
string str = Console.ReadLine();
if (bits.Get(Convert.ToInt32(str)))
Console.WriteLine(str + "是素数!");
else
Console.WriteLine(str + "不是素数!");
}
}
static void BuildSieve(BitArray bits)
{
string primes = "";
//先设置让所有的元素都是true
for (int i = 0; i < bits.Count; i++)
bits.Set(i, true);
//求数组长度的平方根
int lastbit = Convert.ToInt32(Math.Sqrt(bits.Count));
for (int i = 2; i < lastbit; i++)
{
if (bits.Get(i))
{
//一定要float不然会溢出的,这样在有小数的情况下可以保证前一位整数可以进入循环
for (int j = 1; j < (float)(bits.Count) / i; j++)
{
//i*1就是本身,所以要排除,这样j++就排除了这些数是所有倍数,如第一个2,i*j然后j++就排除了4,6,8。。。,而j==1的时候取2就不会排除2本身
bits.Set(i * (j==1?2:j), false);
}
}
}
int count = 0;
for (int i = 2; i < bits.Count; i++)
if (bits.Get(i))
{
primes += i.ToString() + " ";
count++;
}
Console.Write(primes);
}
}
}