Y
Y
yuharu2015-09-30 13:59:13
C++ / C#
yuharu, 2015-09-30 13:59:13

How to reduce the execution time of a program written in C++?

Problem: What is the smallest number n that can be represented as a product n = a∙b in exactly k ways? The products a∙b and b∙a are calculated in the same way, all numbers are natural (1 ≤ k ≤ 50).
Time limit: 1 sec.
With k=50, it takes me more than 2 seconds.
Program code:

int factors(int);

int main()
{
    int k;
  cin>>k;
  cout<<factors(k);
  cout<<endl;
  system("pause");
  return 0;
}

int factors(int k)
{
    int n=0, kol;
  while(true)
  {
    kol=0;
    n++;
    for (int i=n; i>0; i--)
      if (n%i==0)
      {
        if (i*i==n)
          kol=kol+2;
        else kol++;
      }
    if (kol/2==k)
      break;
  }
  return n;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
whiteblackness, 2015-09-30
@whiteblackness

The best way is to change the algorithm. You've got a stupid oversight here.
It is much more efficient to go from the other side of the problem.
Any number can be factorized by the product of prime numbers.
You just need to figure out how many primes your number should factor - and take as many first primes.
You always have 1 pair. 1 * the number itself.
It remains to understand what the number factorization structure should be (how many identical prime numbers should be and how many different ones).

T
Tlito, 2015-10-01
@tlito

I wrote a code that solves this problem, which runs in a maximum of 0.4 seconds on an intel 2GHz quad-core, os ubuntu. the code::blocks compiler displays the time.
you either run on the SDK, or the input wait time is taken into account. in my program, I turned off the input and at k=50 the time is 0.1...0.4 in the picture you can see 0.2
, I don’t know how optimal my program is, but I definitely didn’t understand the comment above on aa|bccdd... aabcc|dd...
I posted the code on the site in the programming column - c++
tlito.ru/node/203

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question