I'm supposed to write a program in C for school where I multiply by 4 but I can't get it to work. When I type 2 I get 20, when I type 3 it's 84, when I type 4 it's 340 and so on, why is that?
#include <stdio.h>
int multi(int i)
{
if (i == 1) {
return 4;
}
if (i == 0) {
return 0;
}
if (i > 1) {
return (multi(i-1)*4)+4;
}
}
int main()
{
int i;
printf("type a numer for multiplication by 4\n");
scanf("%d",&i);
printf("%d * 4 is %d\n",i, multi(i));
}
Multiplying X by Y is adding X Y number of times.
X * Y = X + X + X ...Y times
So change
return (multi(i-1)*4)+4;
to
return multi(i-1) + 4;
and it will work as intended for multiplication by 4.
However, if you want to raise X to the power of Y, you have to multiply X Y number of times.
X to the power of Y = X * X * X...Y times
In this case, there are a couple of more changes you have to make to your code which I leave to you as an exercise.
I'm trying to find numbers that satisfy the clause (x - y * √ 2016) / (y + √ 2016) = 2016.
Number x and y can be rational numbers.
That's what I already tried:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int x, y;
for(x = 1; x < 10000; x++) {
for(y = 1; y < 10000; y++) {
if( (x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) == 2016) {
printf("Numbers are: %d and %d.", x, y);
}
}
}
return 0;
}
Using floating point math and brute force search to "solve" this problem is conceptionally a bad idea. This is because with FP math round-off error propagates in a non-intuitive way, and hence many equations that are solvable in a mathematical sense have no (exact) solution with FP numbers. So using FP math to approximate solutions of mathematical equations is inherently difficult.
I suggest a simplification of the problem before programming.
If one does this and only searches for integer solutions one would find that the only solutions are
x = -2016^2 = -4064256
y = -2016
Why: Just rearrange a bit and obtain
x = 2016*y + (2016 + y)*sqrt(2016)
Since sqrt(2016) is not an integer the term in the clause before the sqrt must be zero. Everything else follows from that.
In case a non-integer solution is desired, the above can be used to find the x for every y. Which even enumerates all solutions.
So this shows that simplification of a mathematical problem before attempted solution in a computer is usually mandatory (especially with FP math).
EDIT: In case you look for rational numbers, the same argument can be applied as for the integer case. Since sqrt(2016) is not a rational number, y must also be -2016. So for the rational case, the only solutions are the same as for the integers, i.e,
x = -2016^2 = -4064256
y = -2016
This is just the equation for a line. Here's an exact solution:
x = (sqrt(2016) + 2016)*y + 2016*sqrt(2016)
For any value of y, x is given by the above. The x-intercept is:
x = 2016*sqrt(2016)
y = 0
The y-intercept is:
x = 0
y = -2016*sqrt(2016)/(sqrt(2016)+2016)
numbers that satisfy (x - y * sqrt(2016.0)) / (y + sqrt(2016.0)) = 2016
Starting with #Tom Karzes
x = (sqrt(2016) + 2016)*y + 2016*sqrt(2016)
Let y = -2016
x = (sqrt(2016) + 2016)*-2016 + 2016*sqrt(2016)
x = 2016*-2016 = -4064256
So x,y = -4064256, -2016 is one exact solution.
With math, this is the only one.
With sqrt(x) not being exactly √x and peculiarities of double math, there may be other solutions that pass a C code simulation.
As a C simulation like OP's, lets us "guess" the answer's x,y are both multiples of 2016 and may be negative.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double f(int x, int y) {
double z = (x - y * sqrt(2016.0)) / (y + sqrt(2016.0));
z = z - 2016;
return z * z;
}
#define M 3000
int main() {
double best_diff = DBL_MAX;
int best_x = 0;
int best_y = 0;
int x, y;
for (x = -M; x < M; x++) {
for (y = -M; y < M; y++) {
double diff = f(x * 2016, y * 2016);
if (diff < best_diff) {
best_diff = diff;
best_x = x;
best_y = y;
}
if (diff == 0) {
printf("Numbers are: %d and %d.\n", best_x*2016, best_y*2016);
}
}
}
if (best_diff != 0.0) {
printf("Numbers are: %d and %d --> %e.", best_x*2016, best_y*2016, best_diff);
}
return 0;
}
Output
Numbers are: -4064256 and -2016.
The result from operations with floats are in general not exact.
Change:
if( (x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) == 2016)
to something like
if( fabs((x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) - 2016) < 0.00000001)
where 0.00000001 is a tolerance chosen by you.
But as pointed out, you don't want to search through the domains of more variables than necessary. Solve the math first. Using Wolfram Alpha like this we get y=(x-24192*√14)/(12*(168+√14))
I wrote a program for finding a root of a fifth degree polynomial, in a range that the user decides as an input.
for example:
Please enter the coefficients of the polynomial:
-64 0 0 0 0 2
Please enter the range:
4 -5.7
Invalid range! Please enter the range:
2 3.5
The polynomial has a root: x=2.
My problem is in when I enter for example the range **10.4 10.2" the program can't compare between two values and decide that its an invalid range. For integers it works.
How do I fix this?
#include <stdio.h>
#define ZERO 0.00001
int main()
{
double a_0,a_1,a_2,a_3,a_4,a_5,end_of_range,beginning_of_range;
int x,root;
printf("Please enter the coefficients of the polynomial:\n");
scanf("%lf%lf%lf%lf%lf%lf", &a_0, &a_1, &a_2, &a_3, &a_4, &a_5);
printf("Please enter the range:\n");
scanf("%lf%lf", &beginning_of_range, &end_of_range);
while (beginning_of_range >= end_of_range)
{
printf("Invalid range! Please enter the range:\n");
scanf("%lf%lf", &beginning_of_range, &end_of_range);
}
x = beginning_of_range;
while (x <= end_of_range)
{
if ((a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x >= -ZERO)
&& (a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x <= ZERO))
{
root = x;
printf("The polynomial has the root x=%d.", root);
break;
}
x++;
if( x > end_of_range)
{
printf("Could not find a root.");
break;
}
}
return 0;
}
Note: I want the roots to be only Integers! that's why I declared x as an int.
And something strange is happening, when I enter the range [10.4, 10.3] it just wait for about 1 minute and then prints "Could not find a root", although it must print invalid range.
Things to change:
Change the type of x. Instead of
int x;
use
double x;
Declare root as a variable.
double root;
Fix the format used to print root. Instead of
printf("The polynomial has the root x=%d.", root);
use
printf("The polynomial has the root x=%lf.\n", root);
Make x a double, but let it only take on integer values.
// x = beginning_of_range;
x = ceil(beginning_of_range);
// while (x <= end_of_range)
while (x <= floor(end_of_range))
// x++
x += 1.0;
This approach will have trouble when |x| is large (about 1/DBL_EPSILON) as x += 1.0; may not result in a incremented x.
BTW:
double y = ((((a_5*x + a_4)*x + a_3)*x + a_2)*x + a_1)*x + a_0;
// is numerically more stable (and likely faster) than
y = (a_0 + a_1*x + a_2*x*x + a_3*x*x*x + a_4*x*x*x*x + a_5*x*x*x*x*x;
Minor: Suggest removing = in range test. A range of [1 1] looks legitimate to me.
// while (beginning_of_range >= end_of_range)
while (beginning_of_range > end_of_range)
I've written some code to Integrate the function 5x^4 + 4x^3 + 3x^2 + 2x + 1.
#include<stdio.h>
#include<math.h>
float func(float x){
float a;
a = 5*pow(x,4) + 4*pow(x,3) + 3*pow(x,2) + 2*x +1;
return a;
}
int main(){
float numberOfXValues;
float a = 0; //lower limit
float b = 1; //upper limit
float numberOfStrips;
float stripSize;
float finalAnswer;
float sumFirstAndLast; //summation of first and last x value
while(1){
printf("Input number of X values:");
scanf("%f", &numberOfXValues);
numberOfStrips = numberOfXValues - 1;
stripSize = (b - a)/(numberOfStrips);
sumFirstAndLast = 0.5*func(a) + 0.5*func(b);
for (float z = stripSize; z < b; z += stripSize ){
sumFirstAndLast += func(z);
}
finalAnswer = sumFirstAndLast * stripSize;
printf("%f\n", finalAnswer);
}
return 0;
}
And it works for the majority of values, but the output for 13 and 20 is giving the wrong answer. I've looked through it a few times but can't see what could be causing this.
Input number of X values:10
5.039070
Input number of X values:11
5.031651
Input number of X values:12
5.026160
Input number of X values:13
6.271982
Input number of X values:14
5.018732
Input number of X values:15
5.016153
Input number of X values:16
5.014071
Input number of X values:17
5.012367
Input number of X values:18
5.010955
Input number of X values:19
5.009773
Input number of X values:20
5.798243
Input number of X values:21
5.007917
The problem is that in the exit condition of the inner loop, you compare two floating point numbers. After numberOfStrips iterations, it's not guaranteed that z == b because of floating point accuracy. It's entirely possible that z < b or z > b. In the z < b case, the loop it executed another time.
You should make numberOfStrips an integer and rewrite the loop like this:
float z = stripSize;
for (int i = 1; i < numberOfStrips; i++) {
sumFirstAndLast += func(z);
z += stripSize;
}
At a first glance this looks to precision and rounding issues of float.
Therefore change float to double.
For example on my machine I get 6.271982 for an input of 10 when using float while I get 5.021983 as result when using double.
Moreover you should use an epsilon in floating point comparisons.
Placing the line:
printf("%f, %d\n", z, z < b);
Inside the for loop will print the z values each iteration along with the loop condition result. The last output of this will be:
1.000000, 1
Which is pointing that we have already reached the right limit, but still performing the loop body. Literally it is thinking that 1.000 < 1.000. It can happen when working with float numbers, so in order to prevent it, consider looping on some integer number (numberOfXValues for example).
Yes, this is a basic C coding homework problem. No, I am not just looking for someone to do it for me. Considering that this is my first programming class, I'm not surprised that I can't get it to work, and I'm certain there is plenty wrong with it. I just want some help pointing out the problems in my code and the things that are missing so that I can fix them on my own.
Homework Question:
Write a program to read ONLY one integer number (your input must be
one 3 digit number from 100 to 999), and to think of a number as
being ABC (where A, B, and C are the 3 digits of a number). Now,
form the number to become ABC, BCA, and CAB, then find out the
remainder of these three numbers when they are divided by 11.
Assume remainders would respectively be X, Y, and Z and add them
up as X+Y, Y+Z, and Z+X. Now if any of these summations is odd
number, increase it by 11 if the summation plus 11 is less than 20,
otherwise decrease the summation by 11 (this summation operation
must be positive number but less than 20). Finally, divide each
of the sums in half. Now, print out all the resulting digits.
My Code:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declare all variables
int OrigNumber;
int x, y, z;
int number;
number = x, y, z;
int sum;
//
printf("Input a three digit number");
//
int c;
c = OrigNumber %10;
//
int b;
b=((OrigNumber - c) % 100)/10;
//
int a;
a = (OrigNumber - (b + c))/100;
//
int abc, bca, cab;
abc = (a*100) + (10*b) + c;
bca = (10*b) + c + (a*100);
cab = c + (a*100) + (10*b);
//
if((number % 2) == 1)
{
if(number + 11 < 20)
number += 11;
else if((100 - 11 > 0) && (100 - 11 < 20))
number -= 11;
}
//
x = abc/11;
y = bca/11;
z = cab/11;
//
sum = (x + y),
(y + z),
(z + x);
}
To start with, you need to read the input. Start with a prompt that includes a carriage return:
printf("Input a three digit number: \n");
Since it's a three digit number, you could add the following line to read the input:
scanf("%3d", &OrigNumber);
The next bit of code works quite well until you get to your if (number % 2) which is meaningless since you didn't really define number - well, you did, but the line
number = x, y, z;
does NOT do what you think it does. If you add
printf("So far I have abc=%d, bca=%d, cab=%d\n", abc, bca, cab);
after you first read in the number and computed those three, you will see you are well on your way.
Note that
number = x, y, z;
Uses a thing called the "comma operator". All the things (a,b,c) are "evaluated" but their values are not returned. At any rate, where you have that line, you didn't yet assign a value to x,y and z.
Is that enough to get your started?
update now that you have had a few hours to mull this over, here are a few more pointers.
Your computation of abc, cab, bca makes no sense. I will show you just one of them:
cab = c*100 + a*10 + b;
Next you need to compute each of x, y and z. Again, here is one of the three:
y = bca%11;
Now you have to make the sums - I call them xy, yz, and zx. Just one of them:
zx = z + x;
Next, to deal with the instruction: "Now if any of these summations is odd number, increase it by 11 if the summation plus 11 is less than 20, otherwise decrease the summation by 11:
if(xy % 2 == 1) {
if(xy + 11 < 20) xy += 11; else xy -= 11;
}
use similar code for all three sums. Then "divide by 2":
xy /= 2;
repeat as needed.
Finally, print out the result:
printf("xy: %d, yz: %d, zx: %d\n", xy, yz, zx);
The amazing thing is that if you did this right, you get the original numbers back...
You could make the code more compact by using an array of values and looping through it - rather than repeating the code snippets I wrote above with different variables. But I suspect that is well outside the scope of what you are expected to know at this point.
Can you take it from here?
#include <stdio.h>
int main()
{
//Declare all variables
int OrigNumber;
int a, b, c;
int abc, bca, cab;
int x, y, z;
int xplusy , yplusz, xplusz;
printf(" A program to read ONLY one integer number.\n Input must be one 3 digit number from 100 to 999 : ");
scanf("%d", &OrigNumber); // Get input from console
if(OrigNumber > 999 || OrigNumber < 100) {
printf("Invalid number. Quiting program. This is error handling. Important while learning programming.");
return 0;
}
c = OrigNumber %10; // digit at unit's place
b=((OrigNumber) % 100)/10; //digit at the ten's place
a = (OrigNumber)/100; //digit at the 100's place. Note: 734/100 = 7. NOT 7.34.
printf("\n Three numbers say A,B, C : %d, %d , %d ", a, b, c);
abc = a*100 + 10*b + c;
bca = 100*b + 10*c + a;
cab = c*100 + a*10 + b;
printf("\n Three numbers say ABC, BCA, CAB : %d, %d , %d ", abc, bca, cab);
x = abc % 11; // Reminder when divided by 11.
y = bca % 11;
z = cab % 11;
printf("\n Three numbers say X, Y, Z : %d, %d , %d ", x, y, z);
xplusy = x + y; // Adding reminders two at a time.
yplusz = y + z;
xplusz = x + z;
printf("\n Three numbers X+Y, Y+Z, X+Z : %d, %d , %d ", xplusy, yplusz, xplusz);
if((xplusy % 2) == 1) {
if(xplusy + 11 < 20)
xplusy += 11;
else
xplusy -= 11;
}
if((yplusz % 2) == 1) {
if(yplusz + 11 < 20)
yplusz += 11;
else
yplusz -= 11;
}
if((xplusz % 2) == 1) {
if(xplusz + 11 < 20)
xplusz += 11;
else
xplusz -= 11;
}
xplusy /= 2; // Finally, divide each of the sum in half.
yplusz /= 2;
xplusz /= 2;
printf("\n Now print out all the resulting digits : %d, %d , %d \n", xplusy, yplusz, xplusz);
return 0;
}
int abc, bca, cab;
abc = (a*100) + (10*b) + c;
bca = (10*b) + c + (a*100);
cab = c + (a*100) + (10*b);
I suggest printing out the numbers at this point in the code.
printf( "%d %d %d", abc, bca, cab );
I think you'll see one of the problems you need to solve.
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int n, a, b, c, abc, bca, cab, x, y, z, p, q, r;
scanf("%d", &n);
c=n%10;
b=(n/10)%10;
a=n/100;
abc=a*100+b*10+c;
bca=b*100+c*10+a;
cab=c*100+a*10+b;
x=abc%11;
y=bca%11;
z=cab%11;
p=x+y;
q=y+z;
r=z+x;
return 0;
}
Now if any of these summations is odd number, increase it by 11 if the
summation plus 11 is less than 20, otherwise decrease the summation by
11 (this summation operation must be positive number but less than
20). Finally, divide each of the sums in half. Now, print out all the
resulting digits.
i didnt get the final part, can you explain it more clearly?