I have a task from my teacher,like :
x^2 + y^3 = z
x filled only with odd
y filled only with even
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
int x,y,z;
int main(){
for (x=1;x<=20;x++){
if ((x%2==1)&&(y%2==0)){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
}
I try to make my own code like above ,but the only one loop is Y , x stand still with 1.
I want to make x to be looping too. What should i do?
My output expectation would be like :
1^2 + 2^3 = 9
3^2 + 4^3 = 71
5^2 + 6^3 = 241
7^2 + 8^3 = 561
9^2 + 10^3 = 1081
11^2 + 12^3 = 1849
13^2 + 14^3 = 2913
15^2 + 16^3 = 4321
17^2 + 18^3 = 6121
19^2 + 20^3 = 8361
PS. Im sorry with my bad english :D
This is what you have:
int main(){
for (x=1;x<=20;x++){
if ((x%2==1)&&(y%2==0)){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
}
The problem is the first if ((x%2==1)&&(y%2==0)){ check.
After the inner for loop is completed, the value of y will be 21. Hence, the above conditional evaluates to false no matter that the value of x is. As a consequence, the inner for loop is executed only once. You need to remove that first if statement.
int main(){
for (x=1;x<=20;x++){
for (y=1;y<=20;y++){
if ((x%2==1)&&(y%2==0)){
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" <<z <<"\n";
}
}
}
}
Update, in response to OP's comment
Looks like you need much simpler code.
int main(){
// Start with x = 1 and increment x by 2. It will be always be odd
for ( x = 1; x <= 20; x += 2 ){
// No need to create another loop. y is simply x+1
// Since x is odd, y will be even.
y = x+1;
// Compute the result and print it.
z = (x*x) + (y*y*y);
cout << "x^2 + y^3 =" << z <<"\n";
}
}
Because y = 21 after the inside y loop.So the x loop will not be executed after . Hope it helpful.
Related
How do I change the following program, so that it performs the same Task, but using only additions and assignments?
I can only do max 27 additions, and the Output has to be generated in a single Input.
Loops and other control flow operations are not allowed
#include <iostream>
int main()
{
int a;
std::cout << "Enter number: ";
std::cin >> a;
std::cout << a*29 << std::endl;
return 0;
}
Another approach that requires 7 +:
int M1 = a; // 1a
int M2 = M1 + M1; // 2a
int M4 = M2 + M2; // 4a
int M8 = M4 + M4; // 8a
int M16 = M8 + M8; // 16a
int res = M16 + M8 + M4 + M1; // 29a
The result is constructed from the binary pattern of the multiplier, i.e. 29 decimal is 0001.1101 binary. So we need to add M16, M8, M4 and M1 (and exclude M2).
This is not general, and it cannot be, but to multiply just by 29 you can do this:
// x is input
int t = x; // x*1
x = x + x;
x = x + x;
t = t + x; // x*5
x = x + x;
t = t + x; // x*13
x = x + x;
t = t + x; // x*29
This is just unrolled binary multiplication, like the similar answers, but without naming the temporary results. The additions to t correspond to the set bits in 29.
This way you can do it with 21 additions.
#include <iostream>
int main()
{
int a;
std::cout << "Enter number: ";
std::cin >> a;
int b = (a+a+...+a) // 10 times
b = b + b;
b = b + (a + a + a ... + a ); // 9 times
std::cout << b << std::endl;
return 0;
}
Can you use an additional var?
b = a + a + a//3 times a
b = b + b + b//9 times a
b = b + b + b//27 times a
b = b + a + a//29 times a
Multiplication is just a repeated addition. Use a loop for this. Do you know how many times your loop should execute? Yes! So use a for loop.
So here is the plan:
Get input
Use a for loop to perform the addition
Output sum
Example:
// get input
int input;
std::cout << "Enter number: ";
std::cin >> input;
// use a for loop to perform the addition
int sum = 0;
for(int i = 0; i< 29; ++i)
sum += a;
// output result
std::cout << sum << std::endl;
,resRepetitive addition is multiplication -- mathematically
So repeat addition of a for n number of times. A simple for/while loop can do this
#include <iostream>
int main()
{
int a,i,temp=0;
std::cout << "Enter number: ";
std::cin >> a;
for(i=1;i<=29;i++)
temp+=a;//add a repeatedly for 'n' number of times. Here 29 as per your requirement. a*n
std::cout << temp <<std::endl;
return 0;
}
Without loop
int b=0,result=0;
b=a+a+a+a+a+a+a;\\adding for 7 times
result=b+b+b+b+a;\\4 times 7 (of a)= 28+a= 29 times (of a).
This involves 10 addition.
You can try this -
b = a + a + a + a + a + a + a + a + a + a + a + a + a + a + a; // equivalent to a*15
b += b -a;
If you are only allowed to use + and =, and are not allowed to cheat by introducing other variables, there is no way of doing this unless you indulge in a bit of undefined behaviour and allow yourself something of the form
... + (a += ...) + ...
where ... is any number of a +. The trick here is that (a += ...) changes the value of a part way through evaluation of the expression.
Tempting as it may be, alas this is not portable C++ since += and + are not sequencing points. On your classroom compiler, you might be able to get this to work.
See https://ideone.com/fC3fai, you can see that
(a + a + a + a + a + (a += a + a + a) + a + a + a + a + a)
does the job on that particular compiler (at the time of writing). (For what it's worth, it also does the correct thing in Java where the expression is well-defined).
You can add value multiple times:
int sum=0;
for(int i=0; i<multipler; i++){
sum+=a; //adds value of a to itself
}
return sum;
If you want to multiple only by 2 you can just shift left:
a = a << 1;
I am working on escape-time fractals as my 12th grade project, to be written in c++ , using the simple graphics.h library that is outdated but seems sufficient.
The code for generating the Mandelbrot set seems to work, and I assumed that Julia sets would be a variation of the same. Here is the code:
(Here, fx and fy are simply functions to convert the actual complex co-ordinates like (-0.003,0.05) to an actual value of a pixel on the screen.)
int p;
x0=0, y0=0;
long double r, i;
cout<<"Enter c"<<endl;
cin>>r>>i;
for(int i= fx(-2); i<=fx(2); i++)
{
for(int j= fy(-2); j>=fy(2); j--)
{
long double x=0.0, y= 0.0,t;
x= gx(i), y= gy(j);
int k= -1;
while(( x*x + y*y <4)&& k<it-1)
{
t= x*x - y*y + r;
y= 2*x*y + i ;
x=t;
k++;
}
p= k*pd;
setcolor(COLOR(colour[p][0],colour[p][1],colour[p][2]));
putpixel(i,j,getcolor());
}
}
But this does not seem to be the case. The output window shows the entire circle of radius=2 with the colour corresponding to an escape time of 1 iteration.
Also, on trying to search for a solution to this problem, I've seen that all the algorithms others have used initializes the initial co-ordinates somewhat like this:
x = (col - width/2)*4.0/width;
y = (row - height/2)*4.0/width;
Could somebody explain what I'm missing out?
I guess that the main problem is that the variable i (imaginary part) is mistakenly overridden by the loop variable i. So the line
y= 2*x*y + i;
gives the incorrect result. This variable should be renamed as, say im. The corrected version is attached below, Since I don't have graphics.h, I used the screen as the output.
#include <iostream>
using namespace std;
#define WIDTH 40
#define HEIGHT 60
/* real to screen */
#define fx(x) ((int) ((x + 2)/4.0 * WIDTH))
#define fy(y) ((int) ((2 - y)/4.0 * HEIGHT))
/* screen to real */
#define gx(i) ((i)*4.0/WIDTH - 2)
#define gy(j) ((j)*4.0/HEIGHT - 2)
static void julia(int it, int pd)
{
int p;
long double re = -0.75, im = 0;
long double x0 = 0, y0 = 0;
cout << "Enter c" << endl;
cin >> re >> im;
for (int i = fx(-2.0); i <= fx(2.0); i++)
{
for (int j = fy(-2.0); j >= fy(2.0); j--)
{
long double x = gx(i), y = gy(j), t;
int k = 0;
while (x*x + y*y < 4 && k < it)
{
t = x*x - y*y + re;
y = 2*x*y + im;
x = t;
k++;
}
p = (int) (k * pd);
//setcolor(COLOR(colour[p][0],colour[p][1],colour[p][2]));
//putpixel(i,j,getcolor());
cout << p; // for ASCII output
}
cout << endl; // for ASCII output
}
}
int main(void)
{
julia(9, 1);
return 0;
}
and the output with input -0.75 0 is given below.
0000000000000000000000000000000000000000000000000000000000000
0000000000000000000001111111111111111111000000000000000000000
0000000000000000011111111111111111111111111100000000000000000
0000000000000001111111111111111111111111111111000000000000000
0000000000000111111111111122222222211111111111110000000000000
0000000000011111111111122222349432222211111111111100000000000
0000000001111111111112222233479743322222111111111111000000000
0000000011111111111222222334999994332222221111111111100000000
0000000111111111112222223345999995433222222111111111110000000
0000011111111111122222234479999999744322222211111111111100000
0000011111111111222222346899999999986432222221111111111100000
0000111111111111222223359999999999999533222221111111111110000
0001111111111112222233446999999999996443322222111111111111000
0011111111111112222233446999999999996443322222111111111111100
0011111111111122222333456899999999986543332222211111111111100
0111111111111122223334557999999999997554333222211111111111110
0111111111111122233345799999999999999975433322211111111111110
0111111111111122233457999999999999999997543322211111111111110
0111111111111122334469999999999999999999644332211111111111110
0111111111111122345999999999999999999999995432211111111111110
0111111111111122379999999999999999999999999732211111111111110
0111111111111122345999999999999999999999995432211111111111110
0111111111111122334469999999999999999999644332211111111111110
0111111111111122233457999999999999999997543322211111111111110
0111111111111122233345799999999999999975433322211111111111110
0111111111111122223334557999999999997554333222211111111111110
0011111111111122222333456899999999986543332222211111111111100
0011111111111112222233446999999999996443322222111111111111100
0001111111111112222233446999999999996443322222111111111111000
0000111111111111222223359999999999999533222221111111111110000
0000011111111111222222346899999999986432222221111111111100000
0000011111111111122222234479999999744322222211111111111100000
0000000111111111112222223345999995433222222111111111110000000
0000000011111111111222222334999994332222221111111111100000000
0000000001111111111112222233479743322222111111111111000000000
0000000000011111111111122222349432222211111111111100000000000
0000000000000111111111111122222222211111111111110000000000000
0000000000000001111111111111111111111111111111000000000000000
0000000000000000011111111111111111111111111100000000000000000
0000000000000000000001111111111111111111000000000000000000000
0000000000000000000000000000000000000000000000000000000000000
would you please tell how you display the image by using these graphics.h library
//setcolor(COLOR(colour[p][0],colour[p][1],colour[p][2]));
//putpixel(i,j,getcolor());
I have 4 variables called: number, x , y, z.
x = 1,
y = 2,
z = 3
I would like the variable number to be able take the values of x, y and z and be able to display value of 123
I have tried this so far:
number = x + y + z; but the answer is 6.
or
number = x << y << z; but the output is not what I want.
Any help would be appreciated.
in C++:
cout << x << y << z
In C:
printf("%d%d%d", x, y, z);
Or to put them in a string:
ostringstream convert; // stream used for the conversion
convert << x << y << z;
std::string result = convert.str();
You can use std::to_string to convert the int to string, then the + operator acts as a concatenation operation.
#include <string>
std::string concatenated = std::to_string(x) + std::to_string(y) + std::to_string(z);
std::cout << concatenated;
Sounds like you may want to convert the characters to strings, perform the string addition, and then convert back to numbers.
This link should help:
[http://www.cplusplus.com/forum/articles/9645/]
You have plenty of ways to get your result :
numerically : number = x * 100 + y * 10 + z
string concatenation as shown by Cyber
directly using characters :
char resul[4];
resul[0] = '0' + x;
resul[1] = '0' + y;
resul[2] = '0' + z;
resul[3] = '\0';
and probably many others ...
I'm trying to create long int multiplication function. In math for multiplying 2 numbers for example 123 X 456, I do:
(12 * 10^1 + 3)( 45 * 10^1 + 6) =
(540 * 10^2) + (72 * 10^1) + (135 * 10^1) + 18 = 15129
I created a small program for this algorithm but it didn't work right.
I don't know where my problem is. Can you help me to understand and correct that?
Tnx
int digits(int n) {
int digit = 0;
while (n>0){
n/=10;
digit++;
}
return digit;
}
long int longMult(long int a, long int b) {
long int x,y,w,z;
int digitA = digits(a);
int digitB = digits(b);
if((a==0) || (b==0)) {
return 0;
} else if (digitA < 2 || digitB < 2) {
return a*b;
} else {
int powA = digitA / 2;
int powB = digitB / 2;
//for first number
x = a/(10^powA);
y = a%(10^powA);
//for second number
w = b/(10^powB);
z = b%(10^powB);
return ( longMult(x,w)*(10^(powA*powB)) + longMult(x,z) +
longMult(w,y)*(10^(powA*powB)) + longMult(y,z));
}
}
int main()
{
cout << digits(23) << endl; // for test
cout << longMult(24,24); // must be 576 but output is 96
return 0;
}
The expression
10^powA
does a bitwise exclusive or, and doesn't raise 10 to the power of powA, as you appear to expect.
You may want to define something like
long powli(int b, long e) {return e?b*powli(b,e-1):1;}
Then instead you can use
powli(10,powA)
Edit: There is also a problem with the way the values are combined:
return ( longMult(x,w)*(10^(powA*powB)) + longMult(x,z) +
longMult(w,y)*(10^(powA*powB)) + longMult(y,z));
Look into the maths, because multiplying the exponents makes little sense.
Also the combinations of adjustments to values is wrong, eg (10*a + b)(10*c + d) = 10*10*a*c + 10*a*d + 10*b*d +b*d. So check on your algebra.
I have a problem, let's say:
Find all two pairs of numbers (x,y) and (z,t) such that x³ + y³ = z³ + t³, where (x, y) != (z, t) and x³ + y³ < 10,000.
Taking the cube root of 10,000 yeilds 21.544 -> round down to 21, so I got:
#include <iostream>
using namespace std;
int main() {
for( int x = 1; x <= 20; ++x ) {
for( int y = x + 1; y <= 21; ++y ) {
for( int z = x + 1; z <= y - 1; ++z ) {
for( int t = z; t <= y - 1; ++t ) {
if( x*x*x + y*y*y == z*z*z + t*t*t ) {
cout << x << ", " << y << ", " << z << ", " << t << endl;
}
}
}
}
}
return 0;
}
I know this code could be optimized more, and that's what I'm looking for. Plus, one of my friends told me that y could be x + 2 instead of x + 1, and I doubt this since if
x = 1, then we will never have y = 2, which in this case missed one possible solution.
Any thought?
Well there's one obvious algorithmic optimization that can be made given the current loop structure, you optimize quite rightly by limiting your ranges to the cube root of 10,000. However you can go farther and limit your range on y based on the cube root of 10,000 - x. That's one thing you can do.
The other optimization is that there's no reason on earth that this should be 4 loops. Simply do 2 loops and compute the values of x^3 + y^3 and check for duplicates. (This is as good as you're going to get without delving into features of cube roots.)
This isn't actually using the API correctly but you get the idea:
multimap<int, std::pair<int, int> > map;
for (int i = 1; i < 21; i++) {
(for int j = x; j < cube_root(10000 - i^3); j++ {
multimap.insert (i^3 + j^3, std::pair<int, int>(i,j);
Then you just iterate through the multimap and look for repeats.
Typical tradeoff: memory for speed.
First the bound on x is quite large: if we suppose that (x,y) is ordered with x <= y, then
x^3 + y^3 < N and x^3 < y^3 (for positive numbers)
=> x^3 + x^3 < N (by transitivity)
<=> x^3 < N/2
<=> x <= floor((N/2)^(1/3))
Thus x <= 17 here.
Now, let us memoize the result of x^3 + y^3 and build an associative table (sum -> pairs). By the way, is there a reason to discard (x,x) as a pair ?
int main(int argc, char* argv[])
{
typedef std::pair<unsigned short, unsigned short> Pair;
typedef std::vector<Pair> PairsList;
typedef std::unordered_map<unsigned short, PairsList> SumMap;
// Note: arbitrary limitation, N cannot exceed 2^16 on most architectures
// because of the choice of using an `unsigned short`
unsigned short N = 10000;
if (argc > 1) { N = boost::lexical_cast<unsigned short>(argv[1]); }
SumMap sumMap;
for (unsigned short x = 1; x*x*x <= N/2; ++x)
{
for (unsigned short y = x; x*x*x + y*y*y <= N; ++y)
{
sumMap[x*x*x + y*y*y].push_back(Pair(x,y));
}
}
for (SumMap::const_reference ref: sumMap)
{
if (ref.second.size() > 1)
{
std::cout << "Sum: " << ref.first
<< " can be achieved with " << ref.second << "\n";
// I'll let you overload the print operator for a vector of pairs
}
}
return 0;
}
We are O(N^2) here.
Make a list of all numbers and their operational result. Sort the list by the results. Test matching results for having different operands.
Use a table from sums to the set of pairs of numbers generating that sum.
You can generate that table by two nested for loops, and then run through the table collecting the sums with multiple solutions.
I'd suggest calculating the powers in outer loops (EDIT: Moved calculations out of the for loops):
int x3, y3, z3;
for( int x = 1; x <= 20; ++x ) {
x3 = x * x * x;
for( int y = x + 1; y <= 21; ++y ) {
y3 = y * y * y;
for( int z = x + 1; z <= y - 1; ++z ) {
z3 = z * z * z;
for( int t = z; t <= y - 1; ++t ) {
if( x3 + y3 == z3 + t*t*t ) {
cout << x << ", " << y << ", " << z << ", " << t << endl;
}
}
}
}
}
Anyway, why do you want to optimize (at least for this example)? This runs in 20 ms on my PC... So I guess you have similar problems at a larger scale.
As a general summary:
Calculate the cubes as you loop rather than at the end, thus int xcubed = x*x*x; just after the loop of x (similarly with y and z). This saves you calculating the same values multiple times. Put them in a table so you only calculate these once.
Create a table of sums of cubes, using a hash_table of some extent, and let it hold duplicates (not to be confused with a hashed-collision).
Any that has a duplicate is a solution.
1729 should come up as one of your solutions by the way. 1 cubed plus 12 cubed and also 9 cubed + 10 cubed.
To test performance you could of course pick a much higher value of maxsum (as well as run it several times).
The algorithm is strictly O(N^2/3). (2/3 because you go only to the cube-root of N and then it is O(m^2) on that smaller range).