How to copy values from one vector to another quickly

Asked

Viewed 1,214 times

2

I’m making a question that the number of elements in the vector are in 10 6 and just wanted to copy certain element to it only that I did the normal way, but common, there is another possibility if make the fastest copy?

for(i = 0; i < teste; i++)
{
    if(primo(vetor[i]))
    {
       aux[cont] = vetor[i];
       cont++;
    }
}

Algorithm to find the prime number

int primo(int num)
{
  int pri = 1, i, raiz = sqrt(num);
  if(num == 2)
  {
    return 1;
  }
  if (num == 1 || num == 0 || num % 2 == 0)
  {
    return 0;
  }
  for(i = 3; i <= raiz; i += 2)
  {
     if(num % i == 0)
     {
         pri = 0;
         break;
     }
  }
   return pri;
}
  • The problem is probably not in the copy but in the calculation of the primes. One way to make a very fast calculation of the primes is by using the algorithm of Sieve of Eratosthenes, which is suitable for calculating primes up to a certain limit number.

1 answer

3


Essentially no. What is probably slowing down is the function primo(). You need to see if the algorithm is the most suitable one (it has a trick with square root), if you cache results, or if you can do some other optimization. Finding big cousins is very slow because it’s exponential.

In theory, in certain situations, there could have been gain using some library that manipulates memory with vector instructions from modern processors or GPU, but it is not always possible to use (this seems to be a case that can not), and is well advanced.

  • hello, cool, I’ll edit the question by placing my prime number code

  • The problem is that then it became another question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.