In general, the task to write a program on c #, without arrays (collections), solves the problem:

Find the length and value of the sum of the elements of a sequence of primes that together give a prime number less than 1000.

You can even describe the algorithm, I think I can code it. Thank you in advance!

  • Yes, bust, what is there to think? Two cycles, external iterates numbers and saves the amount, internal checks for simplicity. - Akina
  • Perhaps I certainly do not understand something, but for example, we have found a simple number, we add it to the sum, but the sum should also be a prime number, how to check that the subsequent addition of several prime numbers will give a prime number in the sum too? - Braxx
  • It seems to me, or the answer is not the only one? For example, 2 and 3 are prime numbers, totaling a prime number of 5. Or 2, 3, 5, and 7 are prime numbers, totaling a prime number of 17. - diraria
  • Serial from the first? - Qwertiy

2 answers 2

Well, just take and check everything for simplicity as needed:

function isPrime(x) { for (var q=2; q*q<=x; ++q) { if (!(x % q)) { return false; } } return true; } for (var x=2, s=0, l=0; s<1000; ++x) { if (isPrime(x)) { ++l; if (isPrime(s+=x)) { console.log(l, s); } } } 

  • 2
    there is no sense to look beyond the root, n / 2 is a bit much, especially on large n - rdorn
  • @rdorn, I agree, corrected. However, the big numbers here and does not smell. - Qwertiy

We can restrict ourselves to checking odd divisors:

  public static bool OddIsPrime(int i) { for (int j = 3; j * j <= i; j += 2) if (i % j == 0) return false; return true; } static void Main(string[] args) // Debug -> Myprojects.Property { int i, sum = 2, len = 1; Console.WriteLine("Последовательности простых чисел с простыми суммами до 1000:"); Console.WriteLine("len = " + len + " sum = " + sum); for (i = 3; sum < 1000; i += 2) if (OddIsPrime(i)) { len++; if ((((sum += i) & 1) == 1) && OddIsPrime(sum)) Console.WriteLine("len = " + len + " sum = " + sum); } } 

The result is the same:

 Sequences of prime numbers with simple sums up to 1000:
 len = 1 sum = 2
 len = 2 sum = 5
 len = 4 sum = 17
 len = 6 sum = 41
 len = 12 sum = 197
 len = 14 sum = 281