Search code examples
c++arraysvectoriterationperfect-square

(C++) Generate first p*n perfect square numbers in an array (p and n inputted from the keyboard)


I input p and n (int type) numbers from my keyboard, I want to generate the first p*n square numbers into the array pp[99]. Here's my code:

#include <iostream>
#include <math.h>

using namespace std;

int main()
{
int i, j, n, p, pp[19];

cout<<"n="; cin>>n;
cout<<"p="; cin>>p;

i=n*p;
j=-1;
while(i!=0)
{
    if(sqrt(i)==(float)sqrt(i))
    {
        j++;
        pp[j]=i;
    }
    i--;
}

for(i=0; i<n*p; i++)
    cout<<pp[i]<<" ";

return 0;
}

But I am encountering the following problem: If I for example I enter p=3 and n=3, it will only show me the first 3 square numbers instead of 9, the rest 6 being zeros. Now I know why this happens, just not sure how to fix it (it's checking the first n * p natural numbers and seeing which are squares, not the first n*p squares).

If I take the i-- and add it in the if{ } statement then the algorithm will never end, once it reaches a non-square number (which will be instant unless the first one it checks is a perfect square) the algorithm will stop succeeding in iteration and will be blocked checking the same number an infinite amount of times.

Any way to fix this?


Solution

  • Instead of searching for them, generate them.

    int square(int x)
    {
        return x * x;
    }
    
    int main()
    {
        int n = 0;
        int p = 0;
        std::cin >> n >> p;
        int limit = n * p;
        int squares[99] = {};
        for (int i = 0; i < limit; i++)
        {
            squares[i] = square(i+1);
        }
        for (int i = 0; i < limit; i++)
        {
            std::cout << squares[i] << ' ';
        }
    }