-1

I am trying to create a program that will prompt a user for an input. From that input I am supposed to print all the prime numbers that are less than and equal to that value. I am really struggling to do this.

I know I need to loop through from 2 to the number. understand what I am missing. This is the code i have so far (all inside main) and when the input is 5 the output is 1 1 which is wrong. What I want to happen (example): if the input is 13 then the output should be 2 3 5 7 11 13.

    int i = 0;
    int getNumber = 0;
    cin >> getNumber;
    

    for (i = 2; i <= getNumber; i++){         
     
        if (getNumber % i == 0){
            prime = false;                      
        }else{
            prime = true;
            
        }
        if (prime == true){
            cout << i << " " << endl;}
    }
  • 1
    Your code appears to use `j` before it has been initialized. – Bill Lynch Sep 10 '21 at 20:19
  • Could you explain, in pseudo code, what you intended your prime validation algorithm to be? Consider if you designed your code to use a function `isPrime(int number)`, how would you use that in a loop? What would that loop iterate over? – Bill Lynch Sep 10 '21 at 20:21
  • Your code also appears to print the variable `prime`, which you have noted in the comments is a boolean. Your problem description says you should be printing an `int`. – Bill Lynch Sep 10 '21 at 20:22
  • 1
    Related: [https://stackoverflow.com/questions/4424374/determining-if-a-number-is-prime](https://stackoverflow.com/questions/4424374/determining-if-a-number-is-prime) – drescherjm Sep 10 '21 at 20:32
  • Are you sure you are checking primality? Suppose `getNumber` equals 57 and in the third iteration of the loop `i` is 4. Then `i` does not divide 57. As a result you go to the `prime = true` branch, even though 4 is certainly _not_ prime. – CiaPan Sep 10 '21 at 20:33
  • Please read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822). Also, you've received 2 answer already but did not react to them. Aren't you interested in getting an answer any more? – zkoza Sep 17 '21 at 09:57

2 Answers2

0

Whenever you enter the else branch you set prime to true and then send it to cout. The boolean value true is output as integer 1. For input number 5 you enter the path twice, hence the result of 1 1.

CiaPan
  • 9,381
  • 2
  • 21
  • 35
0

With this code, you will get all numbers printed less than the input number. You may consider creating a function to check if the "i" is prime & below "n".

Although, effective way is creating two functions- one for checking prime and other for printing the number below entered number. In short you will need 2 for loops.

Rahul
  • 1
  • 1