Reputation: 19
The professor asked us to write a program that printed the first perfect square with the last two digits being odd. Below is my attempt at the problem, I tried different ways of the code to get it it to work but to no avail. I searched around and can't seem to find anyone else with a similar assignment. 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
Upvotes: 1
Views: 2038
Reputation: 183968
The following program prints out all perfect squares whose last two digits (in base 10) are odd:
int main(void){
return 0;
}
If the last digit of n2 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
is of the form 4*m + 1
. But 10 = 2*4 + 2
, so if the penultimate digit is odd, that produces a remainder of 2 modulo 4. To get a number of the form 4*m + 1
, the last digit thus must have the form 4*s + 3
, that means it must be 3 or 7. But no perfect square ends in 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 odd?
Upvotes: 0
Reputation: 97778
Your code is only executing once. You need a loop.
Consider:
i
.main
and your program exits.Nowhere do you say "now go back and try again with this new value of i
". You need a for
or a while
in there.
Upvotes: 1