prime numbers 1-100

May 15, 2020 at 9:00am
I am trying to write a program to print the prime numbers between 1 and 100. Obviusly I am trying with the wrong logic but I can not find the way to fix it. Could someone please help me with it please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cmath>

using namespace std;

void prime();

int main(){
    cout << "Prime numbers: " << endl;
    prime();
}
void prime(){
  for(int number{1}; number <=100; number++){
    for(int i{2}; i<=sqrt(number); i++){
        if(number % i != 0){
            cout << number << endl;
        }
    }
}
}
May 15, 2020 at 9:18am
1
2
3
if(number % i != 0) {
  cout << number << endl;
}


This is where you went wrong. You only are testing one of the possible divisors, instead of all of them, before you cout. I suggest separating the function that determines whether a number is prime from the code that outputs the first 100 primes.
May 15, 2020 at 10:43am
Thank you. I had to count the number of the divisors. It is prime if it has 0 divisor between 2 and the sqrt of the number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cmath>

using namespace std;

void prime();

int main(){
    cout << "Prime numbers: " << endl;
    prime();
}
void prime(){
  for(int number{1}; number <=100; number++){
    int counter{0};
    for(int i{2}; i<=sqrt(number); i++){
        if(number % i == 0){
            counter++;
        }
    }
    if(counter==0){
        cout << number << endl;
    }
  }
}
May 15, 2020 at 11:14am
👌 noice.
May 15, 2020 at 2:07pm
Something like this would be best done using templates and recursive metaprogramming at compile time. Especially when the number of primes you want to print is a compile-time constant.
Jun 2, 2020 at 9:35am
If I want to do it with recursive can I do it with the same logic like I used above? Is it possible to change the nested for function to recursive?
Jun 2, 2020 at 12:49pm
Something like this would be best done using templates and recursive metaprogramming at compile time. Especially when the number of primes you want to print is a compile-time constant.


Just make a const array table of them if you only want 100. There isnt any computation, recursion, etc. needed here. I would even argue that up to 1 million or so in a header file of a const table is fine. The path of least resistance is your friend.

recursion and loops are pretty much interchangeable with a lot of hand waving. I don't know if its been proven 100% but to date no problem has been presented that can't be written as a loop+extras that can be written recursively.
Last edited on Jun 2, 2020 at 12:53pm
Topic archived. No new replies allowed.