c++ - all sums of different prime numbers equals 100 -


i have homework write code, find sums of different prime numbers equals 100. write code 2-elements sums, don't have idea how iterate more elements. has written in c++/clr. happy if me.

#include "stdafx.h" using namespace system; using namespace system::collections::generic;  int main(array<system::string ^> ^args) { list<int> ^primes = gcnew list<int>(); primes->add(2); primes->add(3); (int = 3; < 100; i++) {      double square = math::sqrt(i);     (int j = 2; j <= square ; j++)     {         if(i%j == 0)break;         else if (j == math::floor(square))primes->add(i);     } } int primesquantity = primes->count; int s = 0; (int = 0; < primesquantity; i++) {     (int k = 0; k < primesquantity; k++)     {         if (i != k)         {             s = primes[i] + primes[k];              if (s == 100)             {                 console::writeline("{0}+{1}=" + s, primes[i], primes[k]);             }         }      } } console::readkey(); } 

i forgot name of algorithm idea following:

1) need produce possible combinations of elements. achieved using bit masks. take number , take read bits set 1, example: 5 = 101, take 0 , 2 bits.

2) sum them.

sample of code:

#include <iostream> #include <algorithm> #include <vector>  using namespace std;  int main() {     int primes[] = {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};     vector<vector<int> > res;     // here binary number contains 25 of 1.     // used 25 because number of prime number 1 100     (auto = 0; < 0b1111111111111111111111111; i++)     {         vector<int> group;         auto val = i;         auto bits = 0;         (auto j = val; val; val >>= 1, ++bits)             if (val & 0x1 == 1) group.push_back(bits);         auto sum = std::accumulate(group.begin(), group.end(), 0,         [&primes](int acc, int x){return acc + primes[x];});         if (sum == 100) res.push_back(group);     }      (auto el : res) {         (auto ele : el)             cout << ele << " ";         cout << endl;     }     return 0; } 

result:

0 1 2 3 4 5 6 7 8 0 2 4 5 6 8 9 3 4 5 6 8 9 0 1 4 5 7 8 9 2 4 5 7 8 9 0 1 3 6 7 8 9 2 3 6 7 8 9 .... 1 24 

here indices of elements prime array. aware start 0.

idea improvement: might run body of cycle in new thread since threads don't impact each other


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -