Hey guys, I am having trouble in writing this code. I don't know where to start other than the beginning basic things. I just need to know how to start this thing because I know it is a loop, but loops are my weakest things as of right now. Here is the problem:
P2. (Bulls and Cows)
The number x is called happy if all its digits are different.
Examples: 2541 is a happy number and 2521 is not a happy number.
Let p and q are happy four-digit integers (p > 0, q > 0). Write a program that calculates two other numbers b (bulls) and c (cows) defined in the following way:
- The number b takes the value of the number of pairs of equal digits from p and q with
the same position. The number c takes the value of the number of pairs of equal digits from p and q
having different positions.
Input data: p q
Output: b c
Examples:Input Output
p = 1234, q = 5231 b = 2, c = 1
p = 1234, q = 1234 b = 4, c = 0
p = 4321, q = 5678 b = 0, c = 0
p = 5612, q = 1265 b = 0, c = 4
p = 3451, q = 2415 b = 1, c = 2
After that this is the other question:
To calculate an approximation of the value , a > 0, you can use the following iterative
formula:
xn+1 = 1/3(2xn + a/x^2n) , n >= 0
The approximation of a^1/3, is obtained through the sequence x0, x1, x2......xk starting with x0 = a.
The iteration should stop when the following condition is satisfied:
|(xk-xk-1)/xk| < epsilon for epsilon = 10^-5
or the number of the iteration is greater than 20.
Write a program that prints out the following table:
a a^1/3 pow(a, 1.0/3.0
--- -------- ----------------
0.5 .... ......
1.0 ..... ........
1.5 ..... .........
.... ...... .........
9.0 ......... .........
10.0 ............... ............
where:
- The numbers of the 2nd column are calculated using the iteration formula (1).
- The 3rdcolumn is the corresponding values of the function pow from cmath library.
Note: The numbers in the 2nd and 3rd columns should be printed out by using the manipulator setprecision (5).
Input data: No input data
Output: The table from the above
Here is what I have for this one so far:
int main()
{
double E, x, y, a, c;
a = 0.5;
x = a;
y= a;
E = pow ( 10.0, -5);
while (a < 20 && abs((x -y)/x) <= E)
{x = (1.0/3.0)*(2*x+a/(pow(x,2.0)));
c = pow(a, 1.0/3.0);
a += .5;
y = x;
cout << a << " " << x << " " << c << endl;}}