Home > Blockchain >  Trying to write a C program that lists all the polite numbers in the upper value
Trying to write a C program that lists all the polite numbers in the upper value

Time:09-27

For example, if the user enters the number 21, I want all the polite numbers listed. so for 21, the output would be 3, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21. I am new for loops and I am having a difficult time trying to get this to work. I cant include any global variables for this assignment. Any help would be greatly appreciated. Thank you.

Here is my code so far:

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main() {

//Display a welcome message
std::cout << "Welcome to the polite numbers program" << std::endl;

int upValue;
int number, i, x;
int times = 0;

cout << "What is the upper value? "; //Ask user for upper limit
cin >> upValue; //Stores user input into upValue

while (upValue < 1) //Validate user input of upper limit
{
    cout << "What is the upper value? (must be an integer > 0) ";
    cin >> upValue;
}

for (int i = 3; i <= upValue; i  )
{
    x=sqrt(i);
    if (i!=x*x)
    {
        cout << i << endl;
    }
}

return 0;

}

CodePudding user response:

Seems like you are just excluding the numbers which are squares, which would not produce the right answer. You can either create an array upto upValue with initial value set to 0 and mark all the powers of 2 as 1 using this for loop:

for(int j=1;j<=upValue;j*=2){
    arr[j]=1;
}

now you have flagged all the powers of two and then iterate over the all values from 1 to upValue and print the ones that are set to 0;

CodePudding user response:

The following program does what you want it to do.

#include <iostream>
#include <math.h>
   
    void politeNo(int input)
    {
        // Print all initial input Polite number
        for (int n = 1; n <= input;   n)
        {

            // Calculate nth Polite number
            int result = (int)(n  
                (log((n   (log(n) /
                    log(2))))) /
                log(2));

            // Display calculated result
            std::cout << " " << result;
            if (result == input){break; }
        }
    }
int main()
{
    int upValue = 0;
    std::cout<<" What is the upper value ?";
    std::cin >> upValue; //Stores user input into upValue

    while (upValue < 1) //Validate user input of upper limit
    {
        std::cout << "What is the upper value? (must be an integer > 0) ";
        std::cin >> upValue;
    }
    politeNo(upValue);
    return 0;
}

Output:

1 3 5 6 7 9 10 11 12 13 14 15 17 18 19 20 21
  • Related