Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8525377
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T07:57:40+00:00 2026-06-11T07:57:40+00:00

for( a=1; a <= 25; a++){ num1 = m[a]; for( b=1; b <= 25;

  • 0
for( a=1; a <= 25; a++){
  num1 = m[a];
  for( b=1; b <= 25; b++){
    num2 = m[b];
    for( c=1; c <= 25; c++){
      num3 = m[c];
      for( d=1; d <= 25; d++){
        num4 = m[d];
        for( e=1; e <= 25; e++){
          num5 = m[e];
          for( f=1; f <= 25; f++){
            num6 = m[f];
            for( g=1; g <= 25; g++){
              num7 = m[g];
              for( h=1; h <= 25; h++){
                num8 = m[h];
                for( i=1; i <= 25; i++){
                  num = num1*100000000 + num2*10000000 +
                        num3*  1000000 + num4*  100000 +
                        num5*    10000 + num6*    1000 +
                        num7*      100 + num8*      10 + m[i];
                  check_prime = 1;

                  for ( y=2; y <= num/2; y++)
                  {
                    if ( num % y == 0 )
                      check_prime = 0;
                  }

                  if ( check_prime != 0 )
                  {  
                    array[x++] = num;  
                  }
                  num = 0;  
                }}}}}}}}}

The above code takes a hell lot of time to finish executing.. In fact it doesn’t even finish executing, What can i do to optimize the loop and speed up the execution?? I am newbie to cpp.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T07:57:41+00:00Added an answer on June 11, 2026 at 7:57 am

    You’re checking 259 = 3,814,697,265,625 numbers whether they’re prime. That’s a lot of prime tests and will always take long. Even in the best case (for performance) when all array entries (in m) are 0 (never mind that the test considers 0 a prime), so that the trial division loop never runs, it will take hours to run. When all entries of m are positive, the code as is will run for hundreds or thousands of years, since then each number will be trial-divided by more than 50,000,000 numbers.

    Looking at the prime check,

    check_prime = 1;
    
    for ( y = 2; y <= num/2; y++)
    {
        if ( num % y == 0 )
            check_prime = 0;
    }
    

    the first glaring inefficiency is that the loop continues even after a divisor has been found and the compositeness of num established. Break out of the loop as soon as you know the outcome.

    check_prime = 1;
    
    for ( y = 2; y <= num/2; y++)
    {
        if ( num % y == 0 )
        {
            check_prime = 0;
            break;
        }
    }
    

    In the unfortunate case that all numbers you test are prime, that won’t change a thing, but if all (or almost all, for sufficiently large values of almost) the numbers are composite, it will cut the running time by a factor of at least 5000.

    The next thing is that you divide up to num/2. That is not necessary. Why do you stop at num/2, and not at num - 1? Well, because you figured out that the largest proper divisor of num cannot be larger than num/2 because if (num >) k > num/2, then 2*k > num and num is not a multiple of k.

    That’s good, not everybody sees that.

    But you can pursue that train of thought further. If num/2 is a divisor of num, that means num = 2*(num/2) (using integer division, with the exception of num = 3). But then num is even, and its compositeness was already determined by the division by 2, so the division by num/2 will never be tried if it succeeds.

    So what’s the next possible candidate for the largest divisor that needs to be considered? num/3 of course. But if that’s a divisor of num, then num = 3*(num/3) (unless num < 9) and the division by 3 has already settled the question.

    Going on, if k < √num and num/k is a divisor of num, then num = k*(num/k) and we see that num has a smaller divisor, namely k (possibly even smaller ones).

    So the smallest nontrivial divisor of num is less than or equal to √num. Thus the loop needs only run for y <= √num, or y*y <= num. If no divisor has been found in that range, num is prime.

    Now the question arises whether to loop

    for(y = 2; y*y <= num; ++y)
    

    or

    root = floor(sqrt(num));
    for(y = 2; y <= root; ++y)
    

    The first needs one multiplication for the loop condition in each iteration, the second one computation of the square root outside the loop.

    Which is faster?

    That depends on the average size of num and whether many are prime or not (more precisely, on the average size of the smallest prime divisor). Computing a square root takes much longer than a multiplication, to compensate that cost, the loop must run for many iterations (on average) – whether “many” means more than 20, more than 100 or more than 1000, say, depends. With num larger than 10^8, as is probably the case here, probably computing the square root is the better choice.

    Now we have bounded the number of iterations of the trial division loop to √num whether num is composite or prime and reduced the running time by a factor of at least 5000 (assuming that all m[index] > 0, so that always num >= 10^8) regardless of how many primes are among the tested numbers. If most values num takes are composites with small prime factors, the reduction factor is much larger, to the extent that normally, the running time is almost completely used for testing primes.

    Further improvement can be obtained by reducing the number of divisor candidates. If num is divisible by 4, 6, 8, …, then it is also divisible by 2, so num % y never yields 0 for even y > 2. That means all these divisions are superfluous. By special casing 2 and incrementing the divisor candidate in steps of 2,

    if (num % 2 == 0)
    {
        check_prime = 0;
    } else {
        root = floor(sqrt(num));
        for(y = 3; y <= root; y += 2)
        {
            if (num % y == 0)
            {
                check_prime = 0;
                break;
            }
        }
    }
    

    the number of divisions to perform and the running time is roughly halved (assuming enough bad cases that the work for even numbers is negligible).

    Now, whenever y is a multiple of 3 (other than 3 itself), num % y will only be computed when num is not a multiple of 3, so these divisions are also superfluous. You can eliminate them by also special-casing 3 and letting y run through only the odd numbers that are not divisible by 3 (start with y = 5, increment by 2 and 4 alternatingly). That chops off roughly a third of the remaining work (if enough bad cases are present).

    Continuing that elimination process, we need only divide num by the primes not exceeding √num to find whether it’s prime or not.

    So usually it would be a good idea to find the primes not exceeding the square root of the largest num you’ll check, store them in an array and loop

    root = floor(sqrt(num));
    for(k = 0, y = primes[0]; k < prime_count && (y = primes[k]) <= root; ++k)
    {
        if (num % y == 0)
        {
            check_prime = 0;
            break;
        }
    }
    

    Unless the largest value num can take is small enough, if, for example, you’ll always have num < 2^31, then you should find the primes to that limit in a bit-sieve so that you can look up whether num is prime in constant time (a sieve of 2^31 bits takes 256 MB, if you only have flags for the odd numbers [needs special-casing to check whether num is even], you only need 128 MB to check the primality of numbers < 2^31 in constant time, further reduction of required space for the sieve is possible).

    So far for the prime test itself.

    If the m array contains numbers divisible by 2 or by 5, it may be worthwhile to reorder the loops, have the loop for i the outermost, and skip the inner loops if m[i] is divisible by 2 or by 5 – all the other numbers are multiplied by powers of 10 before adding, so then num would be a multiple of 2 resp. 5 and not prime.

    But, despite all that, it will still take long to run the code. Nine nested loops reek of a wrong design.

    What is it that you try to do? Maybe we can help finding the correct design.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a structure: struct data{ int num1; int num2; int num3; int num4;
say my markup is: <ul> <li id=num1>hello</li> <li id=num2><p>hello</p></li> <li id=num3>sdf dfg</li> <li id=num4></li>
Say I have properties num1, num2, num3 on objectX. I want to take a
For example when I input 2 for num1 and 3 for num2, I expect
I have the following code.... double num1 = Double.parseDouble(textArea_price.getText()); double num2 = Double.parseDouble(textArea_quantity.getText()); double
document.getElementById('num1').innerHTML = homestead[0].textContent; document.getElementById('num3').innerHTML = homestead[1].textContent; } </script> <head> <meta http-equiv=Content-Type content=text/html; charset=utf-8 />
in excel i have a column which contains about 5 numbers cola num1 num2
I have the following table: ID | NUM 1 | 4 2 | 9
So say i had some text like this: line num 1 line num 2
I have data columns: id name type number 1 n1 t1 num1 2 n2

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.