Next Perfect Squares for a Given Number

  • Context: Comp Sci 
  • Thread starter Thread starter mr.me
  • Start date Start date
  • Tags Tags
    C++ Loops Square
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 6K views
mr.me
Messages
49
Reaction score
0
Heres my problem, step one I've solved. Step two only ever returns the original newRoot*newRoo and I don't understand how to correct itTo demonstrate event controlled loops use arithmetic to create:
1.Create a sequence to determine the next largest perfect square
2.Create another sequence to determine the next smallest perfect square for a value less than 1000

My code:

Code:
#include <iostream>
#include <math.h>
#include <iomanip>          
using std::cout;
using std::cin;
using std::endl;

main()
{
   cout << "Enter a number for which to find the next largest perfect square: ";
   int number;
   cin >> number;
   int sqRoot = 1;            
   while (sqRoot*sqRoot < number)  // sqRoot is too small
      sqRoot++;                 //  try the next number
   cout << sqRoot*sqRoot << endl;
   
    cout<< "Enter a number for which to find the next smallest perfect square: ";
    int newNumber;
    cin>>newNumber;
    int newRoot =1000;
    while (newRoot*newRoot < 1000 )
        newRoot-+newRoot;
    cout<< newRoot*newRoot<<endl;
  
}
 
Last edited:
Physics news on Phys.org
I think it is because your while loop is never actually done because 1000*1000>1000

not sure what your trying to do here
newRoot-+newRoot
 
I guess that was an obvious mistake :-p

Still I am not sure how to construct my loop for the problem in question

With the second loop I wanted to check each iteration until a got a value less-than the user entered value...

So if I entered 6 I wanted it to return a 4 because that is the first perfect square less than 6

Im not sure how to do this on paper or with the while loop.
 
hmm... I think you might to try a do while loop and increase the number by 1 each time and check again
 
x=1
y=0
while(y<input)
{
if(x*x>input)
break
y=x*x;
x++
}

count <<y

I think that might do ityou could say "using namespace std" instead of saying all the using at the top
 
Last edited:
Thank-you, I see what I was doing wrong.

We are required to use each std:: for our work, instead of loading the whole namespace.

Thanks again :smile:
 
As an aside, i.e. not homework, what if I wanted to write a square root function, that we allow you to set the given decimal points for stuff like the square of 7 or the square of 10.?

I know C++ already has a sqrt function but could I use my code, clumsy though it may be or would I have to do something entirely different?