i have idea "find primes between 1 and n". Algorithms based on residual division. i use 2 array pr and nt. [pr is saved primes. nt is saved counter number.] ex. begin with 3 3 is primes => pr0 = 3 and nt0 = 2. primes >3 is odd. when i = 5 nt0 = nt0-1 = 1 => 5 is prime. And pr1 = 5, nt1 =pr1 -1 = 4. when i = 7 : nt0 = nt0 -1 = 0, => 7 is prime. and pr2 = 7, nt2 = 6. when i = 9 nt0 < 0 => 9 is not prime. nt0 = pr0 -1 = 2, nt1 = 3, nt2 = 5. ....
using System;
namespace primes
{ // program for find primes between 1 and n.
class Program
{ public static void Main()
{
int[] pr = new int[100], ct = new int[100];
ct[0] = 2;
pr[0] = 3;// 3 is primes => n[0] is 3 .
int n = 1; // n is number of primes.
for (int i = 5; i < 111; i += 2)
{
for (int l = 0; l < n; l++)
{ if (ct[l] >= 0)
{
ct[l]-- ;
//Console.Write("{0} ", ct[l]);
}
else
{
ct[l] = pr[l] - 1 ;
// Console.Write("{0} ", ct[l]);
for (int a = l + 1; a < n; a++)
{
ct[a]--;
// Console.Write("{0} ", ct[a]);
}
// Console.WriteLine();
goto resume; // when ct <0 jump to resume
}
}
// Console.WriteLine();
pr[n] = i;
ct[n] = i ;
// Console.Write("{0} ", ct[n]);
n++;
resume : ;
}
for (int m = 0; m < n; m++)
{
Console.Write(" {0}", pr[m]);
}
Console.ReadKey();
}
}
}
i want to print primes 3,5,7,11, 13... but i when i run: 3 5 7 9 13 15 17 23 29 37 39 63 65 71 89. i dont understand. Can you help me?
答案 0 :(得分:0)
我用错了
if (ct[l] >= 0)
{
ct[l]-- ;
//Console.Write("{0} ", ct[l]);
}
else {
.... goto resume ;
}
当ct [l] <0且ct [k] <0(k> l)=> ct [l] = pr [l] -1时。
但是ct [k] = ct [k] -1。“
if(v != 0)
{ v = 0;// =>i is not prime and v = 0.
}
else {
pr[n] = i;// =>i is prime
ct[n] = i-1 ;
n++;
答案 1 :(得分:-1)
谢谢。 我完成了程序。 这是我的代码:
using System;
namespace primes
{ // program for find primes between 1 and n.
class Program
{ public static void Main()
{
int[] pr = new int[100], ct = new int[100];
ct[0] = 2;
pr[0] = 3;// 3 is primes => n[0] is 3 .
int n = 1;
int v = 0;
for (int i = 5; i < 111; i += 2)
{
for (int l = 0; l < n; l++)
{ if (ct[l] == 0)
{
ct[l] = pr[l] - 1;
v++;
}
else
{
ct[l]--;
}
}
if(v != 0)
{ v = 0;
}
else {
pr[n] = i;
ct[n] = i-1 ;
n++;
}
}
for (int m = 0; m < n; m++)
{
Console.Write(" {0}", pr[m]);
}
Console.ReadKey();
}
}
}