I cannot understand why it is not printing the first perfect square with the last two digits that are odd

The professor asked us to write a program in which the first ideal square was printed, the last two digits being strange. Below is my attempt at a problem, I tried different ways of the code to make it work, but to no avail. I searched around and could not find anyone else with a similar purpose. Any help on this would be greatly appreciated.

// Project3.cpp : main project file. #include "stdafx.h" #include <iostream> #include <cmath> using namespace std; int main() { cout << "This program will attempt to find the first perfect square with the last two digits of the square being odd...\n"; int i = 10; //1. initialize "i" to 10 since square of 1 to 9 are already known to not have 2 odd last digits. int a = i*i; //2. initialize "a" equal to the square of "i". int b = a % 100; //3. initialize "b" to be the remainder of "a" divided by 100 (modulus operator). int c = b / 10; //4. initialize "c" to be b divided by 10, which gives us the "tens" place. int d = a % 10; //5. initialize "d" to be the remainder of "a" divided by 10, giving us the "ones" place. while (((b>10) && (b%2 != 0) && (c%2 != 0) && (d%2 != 0) && ((i*i)%i ==0)) != true){ if ((b>10) && (b%2 != 0) && (c%2 != 0) && (d%2 != 0) && ((i*i)%i ==0)) { cout << "The first perfect square whose last two digits are odd is " << a << ".\n"; system("PAUSE"); return 0; } else { ++i;} } system("PAUSE"); return 0; } 

Thanks Dave

+1
source share
2 answers

Your code is executed only once. You need a loop.

Consider:

  • You run your initialization code.
  • You run if / else, which either displays the output, or outputs, or increments i .
  • Then you get to the end of main , and your program exits.

Nowhere do you say: "Now go back and try again with this new value of i ." You will need for or while .

+1
source

The following program displays all perfect squares, the last two digits of which (in base 10) are odd:

 int main(void){ return 0; } 

If the last digit n 2 is odd, then n itself must be odd, n = 2*k + 1 for some k . Then

 n^2 = (2*k + 1)^2 = 4*k*(k+1) + 1 

has the form 4*m + 1 . But 10 = 2*4 + 2 , therefore, if the penultimate digit is odd, this gives a remainder of 2 modulo 4. To get the form number 4*m + 1 , the last digit must have the form 4*s + 3 , which means that it should be 3 or 7. But there are no perfect square ends at 3 or 7. Therefore, there is no perfect square whose last two digits (in base 10) are odd .

Maybe your professor asked for the first perfect square, whose first two digits are strange?

0
source

Source: https://habr.com/ru/post/953020/


All Articles