Reputation: 25
I am having some trouble understanding what a few lines mean in a code. I recently started learning C++ and picked up Bjarne Stroustrup's "Programming: Principles and Practice Using C++." There is a question in chapter 4 that was tripping me up, so I searched for a solution online to reference. Here is the code I ended up using in conjunction with the book:
#include "std_lib_facilities.h"
bool prime(vector<int> store, int number) {
for (int i = 0; i < store.size(); ++i)
if (number%store[i] == 0) return false; //line that I don't understand
return true;
}
int main() {
int max;
cout << "Please enter a maximum number you want checked for being prime or not.\n";
cin >> max;
vector<int> store;
for (int n = 2; n <= max; ++n)
if (prime(store, n)) store.push_back(n);
for (int n = 0; n < store.size(); ++n)
cout << store[n] << "\n";
keep_window_open();
return 0;
}
The objective of the code is to find all prime numbers below and equal to the user input, starting at 2. I understand everything that is going on in this code with the exception of one line (notated by the comment). What is the purpose of the int "number" on this line, and what mathematically is going on here? The aspect of it that is confusing me is "number" doesn't have a value, yet it is being divided by the value of the current element. If it equals zero, then theoretically the statement is false. Can someone please explain this to me? What does it have to do with finding prime numbers? I want to know what is happening at a basic level so that I may become a more efficient programmer and make my own solution. Thanks.
Upvotes: 1
Views: 80
Reputation: 102
for (int n = 2; n <= max; ++n)
if (prime(store, n)) store.push_back(n);
Here the function is called repeatedly and the value of n is 2 at the beginning as the for loop is iterating n starting from 2. This value of n is the value of number in the function body.
Hope that clears.
Upvotes: 2
Reputation: 11963
The aspect of it that is confusing me is "number" doesn't have a value
number
does have a value: whatever value was passed in the call to prime()
. In main()
, prime()
is called first with number=2, then number=3, ... up to number=max.
Other answers have addressed the mathematical reasoning behind the program.
If you want to understand how this program works - and inspecting the value of number
during a call to prime()
, as well as the call stack, is a great way to do that - I would suggest learning how to use a debugger such as gdb and poking around.
Upvotes: 1
Reputation: 589
In the context of prime
, store
has prime numbers less than number
so far.
number
is a prime if and only if it's not divisible by any integers (beside 0 and 1) smaller than it
Upvotes: 4