So the basics of the coding assignment are we are trying to find all numbers up to a user inputted number that are square pair numbers. A square pair number is two numbers that add up to be a perfect square and subtract to be a perfect square. An example would be 8 + 17 = 25 17 - 8 = 9 or 2 + 2 = 4 2 - 2 = 0. The problem I am having is that I can not figure out any way to code my assignment to make it so that only the square pair numbers appear. I have already formatted the code how it is supposed to look and have included all the invalid options. You can see from the code below that I attempted to try it but was to no success. Thank you to anyone who can help. Maybe Im just being stupid and its really simple.
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int number; // Number entered to find square pairs
char choice; // Character entered on whether or not they wish to continue
cout << "Square numbers are certain pairs of numbers when added together";
cout << " give a \nsquare number and when subtracted also give a square number.\n";
cout << "This program displays all the pairs of a number." << endl;
do {
cout << "\nEnter Number ----> ";
cin >> number;
if (number < 0)
{
cout << "Invalid Number entered, Must be Positive" << endl;
return -1;
}
cout << "\nThe Square Pair Numbers are :- " << endl;
cout << "N\t\tP\t\tN+P\t\tP-N" << endl;
cout << "----------------------------------------------------" << endl;
for (int n = 0; n < number; n++)
{
for(int p = 0; p < number ; p++)
{
if (sqrt(n+p) == 0)
{
cout << n << "\t\t" << p << "\t\t" << p+n << "\t\t" << p-n << endl;
}
}
}
cout << "\n\nWould you like to repeat the process for another number?" << endl;
cout << "Enter Y,y or N,n ---------> ";
cin >> choice;
if (choice != 'y' & choice != 'Y' && choice != 'n' && choice != 'N')
{
cout << "Invalid option, Choose y,Y or N,n" << endl;
return -2;
}
}
while (choice != 'n' && choice != 'N');
{
cout << "\nPROGRAM TERMINATED" << endl;
cout << "\n\nSquare Numbers is Prepared by Taylor Burcham";
cout << "\nGame Playing with Computers , Inc.";
cout << "\n10 - 21 - 2015" << endl;
return -9;
}
return 0;
}
First some small things:
Line 39: change & to &&
Lines 46 and 52: No need for the braces.
Line 51: You should return 0 on success. This makes it easier to use your program in a shell script.
Line 67: This is never reached.
Line 27: There's no need to repeat numbers is there? The code will be easier if p goes from 0 to n instead of 0 to number.
Now for the crux of the problem: how to tell if p and q meet the requirements? You want to see if the square root of the numbers is an integer. To do this you can use floor(), which rounds a double down to the nearest integer:
Thank you so much. The code seems to be working perfectly fine now. I will let you know if my professor says i need to change anything. For real youre a life saver.