c++ - code runs well for small input but acts like an infinite loop when input is big -


I am trying to solve a problem that wants to connect the two million people to the Prime Minister and his yoga and my Showing totals as output (see for more information). I have written this code

  #include & lt; Iostream & gt; using namespace std; int main () {int last_range; Int not_prime_counter = 0; Int sum = 0; Int prime_number_counter = 0; Cout & lt; & Lt; "From 2 to the limit"; CIN & gt; & Gt; Last_range; Int input = 2; / * If (input == 1) {cout & lt; & Lt; Input & lt; & Lt; "Prime \ n"; Yoga = yoga + input; Input ++; } * / If (input == 2) {cout & lt; & Lt; Input & lt; & Lt; "Prime \ n"; Yoga = yoga + input; Cout & lt; & Lt; "Yoga:" & lt; & Lt; Sum & lt; & Lt; Endl; Input ++; Prime_number_counter ++; } If (input == 3) {cout & lt; & Lt; Input & lt; & Lt; "Prime \ n"; Yoga = yoga + input; Cout & lt; & Lt; "Yoga:" & lt; & Lt; Sum & lt; & Lt; Endl; Input ++; Prime_number_counter ++; } If (Input> 3) {for (int i = 2; i & lt; = (Input / 2); i ++) {if (input == last_range) {break; } If (input% i == 0) {// cout & lt; & Lt; Input & lt; & Lt; "Is not prime \ n"; Input ++; I = 2; } If (I == (Input / 2) & amp; amp; not_prime_counter == 0) {cout & lt; & Lt; Input & lt; & Lt; "Prime \ n"; Yoga = yoga + input; Cout & lt; & Lt; "Yoga:" & lt; & Lt; Sum & lt; & Lt; Endl; Input ++; I = 2; }}} Cout & lt; & Lt; "Last amount:" & lt; & Lt; Sum & lt; & Lt; Endl; System ("pause"); Return 0; }   

It works well for 100,200, but when the input is 2000000, it always runs for it. I want to know why this is happening and what is the solution to my problem? I want to use a single for loop.

Your algorithm for large input is too slow to determine if a number is prime or not , You only have to check up to its square.

It is a clean and fast to check if a number is prime or not:

  bool prime (int n) {if (n == 1) return false ; If (n == 2) true return; If (n% 2 == 0) returns incorrectly; For (i = 3; i * i & lt; = n; i + = 2) if returns (n% i == 0) wrong; Back true; }    

Comments

Popular posts from this blog

php - PDO bindParam() fatal error -

logging - How can I log both the Request.InputStream and Response.OutputStream traffic in my ASP.NET MVC3 Application for specific Actions? -

java - Why my included JSP file won't get processed correctly? -