Misunderstood topic - c

Define a function CoordTransform() that transforms its first two input
parameters xVal and yVal into two output parameters xValNew and
yValNew. The function returns void. The transformation is new = (old +
1) * 2. Ex: If xVal = 3 and yVal = 4, then xValNew is 8 and yValNew is
10.
Question: I have to make this code, it is for homework in a text book. I'm not quite understanding the whole section. So, I'm asking for help and an explanation. Thank you!
My code is as followed:
#include <stdio.h>
/* Your solution goes here */
void CoordTransform( int* xValNew, int* yValNew)
{
*xValNew = ((xValNew +1) * 2);
*yValNew = ((yValNew +1) * 2);
return;
}
int main(void) {
int xValNew = 0;
int yValNew = 0;
CoordTransform(3, 4, &xValNew, &yValNew);
printf("(3, 4) becomes (%d, %d)\n", xValNew, yValNew);
return 0;
}

the code for the CoordTransform() should be like:
#include <stdio.h>
void CoordTransform(int xVal, int yVal, int *xValNew, int *yValNew) {
*xValNew = ((xVal +1) * 2);
*yValNew = ((yVal +1) * 2);
}
int main(void) {
int xValNew;
int yValNew;
CoordTransform(3, 4, &xValNew, &yValNew);
printf("(3,4) becomes (%d, %d)\n", xValNew, yValNew);
return 0;
}
The main purpose for this exercice is to distinguish between passing parameters by value like xVal and yVal in order to use the values without changing them, and passing parameters by address or reference like xValNew and yValNew if you intend to change the value of these output parameters.

You specs say "... transforms its first two input parameters xVal and yVal into two output parameters xValNew and yValNew" so your function should have four parameters, not two:
/* Your solution goes here */
void CoordTransform( int xVal, int yVal, int* xValNew, int* yValNew)
{
*xValNew = ((xVal +1) * 2);
*yValNew = ((yVal +1) * 2);
}
int main(void) {
int xValNew;
int yValNew;
CoordTransform(3, 4, &xValNew, &yValNew);
printf("(3, 4) becomes (%d, %d)\n", xValNew, yValNew);
return 0;
}

you are giving 4 parameters to a function that accepts only 2, and in your function CoordTransform, you should dereference the pointers to get the values
/* Your solution goes here */
void CoordTransform( int* xValNew, int* yValNew)
{
*xValNew = ((*xValNew +1) * 2);
*yValNew = ((*yValNew +1) * 2);
return;
}
( the return statement is not needed since the type of your function is void )

I encountered the same problem in my c++ class...
However I haven't learned C, so perhaps it doesn't allow '&' referencing? And only uses '*' for pointers?
My solution:
#include <iostream>
using namespace std;
/* Your solution goes here */
void CoordTransform(int xVal, int yVal, int& xValNew, int& yValNew) {
xValNew = (xVal + 1) * 2;
yValNew = (yVal + 1) * 2;
}
int main() {
int xValNew;
int yValNew;
int xValUser;
int yValUser;
cin >> xValUser;
cin >> yValUser;
CoordTransform(xValUser, yValUser, xValNew, yValNew);
cout << "(" << xValUser << ", " << yValUser << ") becomes (" << xValNew << ", " << yValNew << ")" << endl;
return 0;
}
I used a previous example as reference:
#include <iostream>
using namespace std;
void ConvHrMin(int timeVal, int& hrVal, int& minVal) {
hrVal = timeVal / 60;
minVal = timeVal % 60;
}
int main() {
int totTime;
int usrHr;
int usrMin;
totTime = 0;
usrHr = 0;
usrMin = 0;
cout << "Enter total minutes: ";
cin >> totTime;
ConvHrMin(totTime, usrHr, usrMin);
cout << "Equals: ";
cout << usrHr << " hrs ";
cout << usrMin << " min" << endl;
return 0;
}
which outputs this (with 156 input):
Enter total minutes: 156
Equals: 2 hrs 36 min

Related

Function calculate results wrong answer

I'm doing an exercise and I stuck with my code. I hope you guys can help me fix it.
And here is my function fen():
double fen(double x,double y, int n) { // You should complete this function
// Write your statements here
double sum=1,temp;
int j=2,k=1;
double a = (x*y*y) / 18;
sum=1-a;
for(int i=2;i<=n;i++)
{
for(;j<=i;j++)
{
a *= (x*y);
for(;k<=(i+j);k++)
a /= k;
}
temp = a/(k*k);
temp = (i%2 == 0) ? temp : -temp;
sum+=temp;
}
return sum; //This statement must be changed
}
I've checked many times but still don't know why its result's wrong.
I've debugged and when i=3, a actually equal to 0.025 but it displayed0.02499999999.
I wrote a small code to simplify things and here it is:
#include <iostream>
using namespace std;
double fen(double x,double y, int n) {
double tmp = y;
double sum = 1;
for (int i = 1; i < n; i++) {
tmp *= -((x * y * (2*i-1)) / ((2*i) * (2*i+1) * (2*i+1)));
sum += tmp;
}
return sum;
}
int main(void) {
cout << fen(2,3,1) << endl;
cout << fen(2,3,2) << endl;
cout << fen(2,3,3) << endl;
cout << fen(2,3,4) << endl;
cout << fen(2,3,1000) << endl;
return 0;
}
I only checked it till fen(2,3,4) and results were correct till there. it shows 0.162772 for fen(2,3,1000):
1
0
0.18
0.161633
0.162772
UPDATE:
Updated code to use cout for output rather than printf. But I don't think this code really differs between C or C++.
In addition, remember that you reach quickly to limit of numerical precision of double in this code.
OP's formula mis-calculates the terms.
// int j=2,k=1;
int j=2,k=3; // The loop's later calculation expect this to be initially 3
// in the loop
// add
a *= k; // undo the prior terms /k
for(;j<=i;j++) {
// this part OK
}
// temp = a/(k*k);
temp = a/k*; // Only need /k
Other simplifications possible.

Instead of printing the binary number out how would I store it as a variable?

I pass in a hex number into hex2bin and it prints out the binary number correctly but I don't want it to print out the number I want to return the number so I can use it to find the cardinality of the number. How would I store the number instead of printing it out?
int hex2bin (int n){
int i,k,mask;
for(i = sizeof(int) * 8 - 1; i >= 0; i--){
mask = 1 << i;
k = n & mask;
k == 0 ? printf("0"):printf("1");
}
return 0;
}
Perhaps something like this?
int result = 0;
int i, k...
...
result = result | (((k == 0) ? 0 : 1) << i;
...
return result;
Instead of being clever with an int, you could of course also simply use an array of variables instead.
Store the number in a string whose space is provided by a compound literal (Available since C99).
It works like OP's flow: Loop up to sizeof(int) * 8 times, finding the value of 1 bit and print/save it.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Maximum buffer size needed
#define UTOA_BASE_2 (sizeof(unsigned)*CHAR_BIT + 1)
char *utoa_base2(char *s, unsigned x) {
s += UTOA_BASE_2 - 1;
*s = '\0';
do {
*(--s) = "01"[x % 2];
x /= 2;
} while (x);
return s;
}
#define TO_BASE2(x) utoa_base2((char [UTOA_BASE_2]){0} , (x))
void test(unsigned x) {
printf("base10:%10u base2:%5s ", x, TO_BASE2(x));
char *s = TO_BASE2(x);
// do stuff with `s`, it is valid for until the end of this block
printf("%s\n", s);
}
int main(void) {
test(0);
test(25);
test(UINT_MAX);
}
Sample output
base10: 0 base2: 0 0
base10: 25 base2:11001 11001
base10:4294967295 base2:11111111111111111111111111111111 11111111111111111111111111111111
This is a variation of this base-n answer.
You can use the strcat function to do that.
Note that the new hex2bin function in this answer assumes that the parameter char *buf has already been allocated and can hold at least 1+sizeof(int)*8 bytes including the null terminator:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// assume: buf is at least length 33
int hex2bin (int n, char *buf)
{
int i,k,mask;
for(i = sizeof(int) * 8 - 1; i >= 0; i--){
mask = 1 << i;
k = n & mask;
k == 0 ? strcat(buf, "0") : strcat(buf, "1");
}
return 0;
}
int main()
{
int n = 66555;
char buffer[1+sizeof(int)*8] = { 0 } ;
hex2bin(n, buffer);
printf("%s\n", buffer);
return 0;
}
I hope you will find this helpful :)
bool convertDecimalBNR(INT32 nDecimalValue, UINT32 * punFieldValue, INT32 nBitCount, DecimalBNRType * pDecimalSpecification)
{
bool bBNRConverted = false;
INT32 nBitIndex = nBitCount - 1;
INT32 nBitValue = anTwoExponents[nBitIndex];
*punFieldValue = 0;
if ((nDecimalValue >= pDecimalSpecification->nMinValue) && (nDecimalValue <= pDecimalSpecification->nMaxValue))
{
// if the value is negative, then add (-1 * (2 ^ (nBitCount - 1))) on itself and go on just like a positive value calculation.
if (nDecimalValue < 0)
{
nDecimalValue += nBitValue;
nBitIndex--;
nBitValue /= 2;
*punFieldValue |= BIT_0_ONLY_ONE;
}
while (nBitIndex >= 0)
{
*punFieldValue = (*punFieldValue << 1);
if (nDecimalValue >= nBitValue)
{
nDecimalValue -= nBitValue;
*punFieldValue |= BIT_0_ONLY_ONE;
}
nBitIndex--;
nBitValue /= 2;
}
if (nDecimalValue <= nBitValue)
{
bBNRConverted = true;
}
}
return (bBNRConverted);
}

Why does this bitwise operation return 30 instead of 384?

I am using Dev-C++ compiler. This program is supposed to print 30 but its printing 384.
#include <stdio.h>
int main() {
int n = 3;
int ans;
ans = n<<3 + n<<1;
printf("%d", ans);
getch();
return 0;
}
The problem is that the + operator has higher precedence than the << operator. What you wrote actually means:
ans = n << (3 + n) << 1;
What you actually want is:
ans = (n<<3) + (n<<1);

gsl multiroot iteration trying nan?

I am trying to find the right parameters to input to my code to produced the desired results. Instead of guessing and checking I am using a root find to find the parameters that give the desired results. There are two variables that are free to vary, but I was having difficulty running the root finder. I changed the code to solve for each variable individually and found out that I was having trouble optimizing one variable.
It seems that the problem is that gsl_multiroot_iterate is guessing nan for x1 after the first iteration. At least that is what the value of x1 is returning in the function() call after that point, when I put in a printf statement for x1.
The simulation I am running only allows values of x1 between 0 and 1. It could be possible that this is causing the issue, though I check in the simulation to make sure x1 is between 0 and 1, and never throws an issue besides when x1 is nan. Is there anyway to set a range for what values the iteration tries for x1? And would anyone know what the iteration tries using nan for x1?
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_multiroots.h>
struct rparams{
double target1;
};
int function(const gsl_vector * x, void *params, gsl_vector * f);
int main(int argc, char* argv[]) {
double target1;
sscanf(argv[1],"%lf",&target1);
const gsl_multiroot_fsolver_type *T;
gsl_multiroot_fsolver *s;
int status;
unsigned int iter = 0;
const size_t n = 1;
struct rparams p;
p.target1 = target1;
gsl_multiroot_function f = {&function, n, &p};
double x_init[1] = {.1};
gsl_vector * x = gsl_vector_alloc(n);
gsl_vector_set(x, 0, x_init[0]);
T = gsl_multiroot_fsolver_hybrid;
s = gsl_multiroot_fsolver_alloc(T, 1);
gsl_multiroot_fsolver_set(s, &f, x);
print_state(iter, s);
do
{
iter++;
status = gsl_multiroot_fsolver_iterate (s);
print_state(iter, s);
/* check if solver is stuck */
if (status){
break;
}
status = gsl_multiroot_test_residual (s->f, 1e-7);
}
while (status == GSL_CONTINUE && iter < 1000);
printf("status = %s\n", gsl_strerror (status));
gsl_multiroot_fsolver_free (s);
gsl_vector_free (x);
return 0;
}
int function(const gsl_vector * x, void *params, gsl_vector * f){
double target1 = ((struct rparams *) params)->target1;
double x1 = gsl_vector_get(x, 0);
/* Run simulation here using x1 parameter */
/* Assign output to temp1, which I am trying to match to target1 */
const double y1 = temp1 - target1;
gsl_vector_set (f, 0, y1);
return GSL_SUCCESS;
}
Be careful in designing the function you want to obtain the root from. In fact, for a test, I tried a function that had a constant output. This caused the algorithm to throw out the NaNs.
If you only need to find the root of a single equation, you can use the gsl_roots library instead of gsl_multiroots. The gsl_roots library has several bisection algorithms for which you specify a range instead of an initial guess. If you know your root is inside the interval (0, 1), you would set that as the target interval and the algorithm would never go outside that range. A minimal, complete example in C++ demonstrating the bisection method is below. If you can't use C++11 lambda functions, then you'd have to define the objective function like you did in your original question.
#include <iostream>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_roots.h>
using namespace std;
int
main (void)
{
//Set the solver type (bisection method)
gsl_root_fsolver* s = gsl_root_fsolver_alloc(gsl_root_fsolver_bisection);
//Use a lambda to define the objective function.
//This is a parabola with the equation: y = (x-1)^2 - 1
//It has roots at x = 0 and x = 2.
gsl_function F;
F.function = [](double x, void*){return ((x-1) * (x-1)) - 1;};
//Initialize the solver; make a guess that the root is between x = 0.5 and x = 10
gsl_root_fsolver_set(s, &F, 0.5, 10.0);
//Run the solver until the root is found to within 0.001
int status;
do {
gsl_root_fsolver_iterate(s);
double r = gsl_root_fsolver_root(s);
double x_low = gsl_root_fsolver_x_lower(s);
double x_high = gsl_root_fsolver_x_upper(s);
status = gsl_root_test_interval(x_low, x_high, 0, 0.001);
if (status == GSL_SUCCESS)
cout << "Converged" << endl;
cout << "x_low = " << x_low;
cout << "; x_high = " << x_high;
cout << "; root = " << r << endl;
}
while (status == GSL_CONTINUE);
return status;
}

Divide a number by 3 without using *, /, +, -, % operators

How would you divide a number by 3 without using *, /, +, -, %, operators?
The number may be signed or unsigned.
This is a simple function which performs the desired operation. But it requires the + operator, so all you have left to do is to add the values with bit-operators:
// replaces the + operator
int add(int x, int y)
{
while (x) {
int t = (x & y) << 1;
y ^= x;
x = t;
}
return y;
}
int divideby3(int num)
{
int sum = 0;
while (num > 3) {
sum = add(num >> 2, sum);
num = add(num >> 2, num & 3);
}
if (num == 3)
sum = add(sum, 1);
return sum;
}
As Jim commented this works, because:
n = 4 * a + b
n / 3 = a + (a + b) / 3
So sum += a, n = a + b, and iterate
When a == 0 (n < 4), sum += floor(n / 3); i.e. 1, if n == 3, else 0
Idiotic conditions call for an idiotic solution:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp=fopen("temp.dat","w+b");
int number=12346;
int divisor=3;
char * buf = calloc(number,1);
fwrite(buf,number,1,fp);
rewind(fp);
int result=fread(buf,divisor,number,fp);
printf("%d / %d = %d", number, divisor, result);
free(buf);
fclose(fp);
return 0;
}
If also the decimal part is needed, just declare result as double and add to it the result of fmod(number,divisor).
Explanation of how it works
The fwrite writes number bytes (number being 123456 in the example above).
rewind resets the file pointer to the front of the file.
fread reads a maximum of number "records" that are divisor in length from the file, and returns the number of elements it read.
If you write 30 bytes then read back the file in units of 3, you get 10 "units". 30 / 3 = 10
log(pow(exp(number),0.33333333333333333333)) /* :-) */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int num = 1234567;
int den = 3;
div_t r = div(num,den); // div() is a standard C function.
printf("%d\n", r.quot);
return 0;
}
You can use (platform dependent) inline assembly, e.g., for x86: (also works for negative numbers)
#include <stdio.h>
int main() {
int dividend = -42, divisor = 5, quotient, remainder;
__asm__ ( "cdq; idivl %%ebx;"
: "=a" (quotient), "=d" (remainder)
: "a" (dividend), "b" (divisor)
: );
printf("%i / %i = %i, remainder: %i\n", dividend, divisor, quotient, remainder);
return 0;
}
Use itoa to convert to a base 3 string. Drop the last trit and convert back to base 10.
// Note: itoa is non-standard but actual implementations
// don't seem to handle negative when base != 10.
int div3(int i) {
char str[42];
sprintf(str, "%d", INT_MIN); // Put minus sign at str[0]
if (i>0) // Remove sign if positive
str[0] = ' ';
itoa(abs(i), &str[1], 3); // Put ternary absolute value starting at str[1]
str[strlen(&str[1])] = '\0'; // Drop last digit
return strtol(str, NULL, 3); // Read back result
}
(note: see Edit 2 below for a better version!)
This is not as tricky as it sounds, because you said "without using the [..] + [..] operators". See below, if you want to forbid using the + character all together.
unsigned div_by(unsigned const x, unsigned const by) {
unsigned floor = 0;
for (unsigned cmp = 0, r = 0; cmp <= x;) {
for (unsigned i = 0; i < by; i++)
cmp++; // that's not the + operator!
floor = r;
r++; // neither is this.
}
return floor;
}
then just say div_by(100,3) to divide 100 by 3.
Edit: You can go on and replace the ++ operator as well:
unsigned inc(unsigned x) {
for (unsigned mask = 1; mask; mask <<= 1) {
if (mask & x)
x &= ~mask;
else
return x & mask;
}
return 0; // overflow (note that both x and mask are 0 here)
}
Edit 2: Slightly faster version without using any operator that contains the +,-,*,/,% characters.
unsigned add(char const zero[], unsigned const x, unsigned const y) {
// this exploits that &foo[bar] == foo+bar if foo is of type char*
return (int)(uintptr_t)(&((&zero[x])[y]));
}
unsigned div_by(unsigned const x, unsigned const by) {
unsigned floor = 0;
for (unsigned cmp = 0, r = 0; cmp <= x;) {
cmp = add(0,cmp,by);
floor = r;
r = add(0,r,1);
}
return floor;
}
We use the first argument of the add function because we cannot denote the type of pointers without using the * character, except in function parameter lists, where the syntax type[] is identical to type* const.
FWIW, you can easily implement a multiplication function using a similar trick to use the 0x55555556 trick proposed by AndreyT:
int mul(int const x, int const y) {
return sizeof(struct {
char const ignore[y];
}[x]);
}
It is easily possible on the Setun computer.
To divide an integer by 3, shift right by 1 place.
I'm not sure whether it's strictly possible to implement a conforming C compiler on such a platform though. We might have to stretch the rules a bit, like interpreting "at least 8 bits" as "capable of holding at least integers from -128 to +127".
Here's my solution:
public static int div_by_3(long a) {
a <<= 30;
for(int i = 2; i <= 32 ; i <<= 1) {
a = add(a, a >> i);
}
return (int) (a >> 32);
}
public static long add(long a, long b) {
long carry = (a & b) << 1;
long sum = (a ^ b);
return carry == 0 ? sum : add(carry, sum);
}
First, note that
1/3 = 1/4 + 1/16 + 1/64 + ...
Now, the rest is simple!
a/3 = a * 1/3
a/3 = a * (1/4 + 1/16 + 1/64 + ...)
a/3 = a/4 + a/16 + 1/64 + ...
a/3 = a >> 2 + a >> 4 + a >> 6 + ...
Now all we have to do is add together these bit shifted values of a! Oops! We can't add though, so instead, we'll have to write an add function using bit-wise operators! If you're familiar with bit-wise operators, my solution should look fairly simple... but just in-case you aren't, I'll walk through an example at the end.
Another thing to note is that first I shift left by 30! This is to make sure that the fractions don't get rounded off.
11 + 6
1011 + 0110
sum = 1011 ^ 0110 = 1101
carry = (1011 & 0110) << 1 = 0010 << 1 = 0100
Now you recurse!
1101 + 0100
sum = 1101 ^ 0100 = 1001
carry = (1101 & 0100) << 1 = 0100 << 1 = 1000
Again!
1001 + 1000
sum = 1001 ^ 1000 = 0001
carry = (1001 & 1000) << 1 = 1000 << 1 = 10000
One last time!
0001 + 10000
sum = 0001 ^ 10000 = 10001 = 17
carry = (0001 & 10000) << 1 = 0
Done!
It's simply carry addition that you learned as a child!
111
1011
+0110
-----
10001
This implementation failed because we can not add all terms of the equation:
a / 3 = a/4 + a/4^2 + a/4^3 + ... + a/4^i + ... = f(a, i) + a * 1/3 * 1/4^i
f(a, i) = a/4 + a/4^2 + ... + a/4^i
Suppose the reslut of div_by_3(a) = x, then x <= floor(f(a, i)) < a / 3. When a = 3k, we get wrong answer.
To divide a 32-bit number by 3 one can multiply it by 0x55555556 and then take the upper 32 bits of the 64 bit result.
Now all that's left to do is to implement multiplication using bit operations and shifts...
Yet another solution. This should handle all ints (including negative ints) except the min value of an int, which would need to be handled as a hard coded exception. This basically does division by subtraction but only using bit operators (shifts, xor, & and complement). For faster speed, it subtracts 3 * (decreasing powers of 2). In c#, it executes around 444 of these DivideBy3 calls per millisecond (2.2 seconds for 1,000,000 divides), so not horrendously slow, but no where near as fast as a simple x/3. By comparison, Coodey's nice solution is about 5 times faster than this one.
public static int DivideBy3(int a) {
bool negative = a < 0;
if (negative) a = Negate(a);
int result;
int sub = 3 << 29;
int threes = 1 << 29;
result = 0;
while (threes > 0) {
if (a >= sub) {
a = Add(a, Negate(sub));
result = Add(result, threes);
}
sub >>= 1;
threes >>= 1;
}
if (negative) result = Negate(result);
return result;
}
public static int Negate(int a) {
return Add(~a, 1);
}
public static int Add(int a, int b) {
int x = 0;
x = a ^ b;
while ((a & b) != 0) {
b = (a & b) << 1;
a = x;
x = a ^ b;
}
return x;
}
This is c# because that's what I had handy, but differences from c should be minor.
It's really quite easy.
if (number == 0) return 0;
if (number == 1) return 0;
if (number == 2) return 0;
if (number == 3) return 1;
if (number == 4) return 1;
if (number == 5) return 1;
if (number == 6) return 2;
(I have of course omitted some of the program for the sake of brevity.) If the programmer gets tired of typing this all out, I'm sure that he or she could write a separate program to generate it for him. I happen to be aware of a certain operator, /, that would simplify his job immensely.
Using counters is a basic solution:
int DivBy3(int num) {
int result = 0;
int counter = 0;
while (1) {
if (num == counter) //Modulus 0
return result;
counter = abs(~counter); //++counter
if (num == counter) //Modulus 1
return result;
counter = abs(~counter); //++counter
if (num == counter) //Modulus 2
return result;
counter = abs(~counter); //++counter
result = abs(~result); //++result
}
}
It is also easy to perform a modulus function, check the comments.
This one is the classical division algorithm in base 2:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint32_t mod3[6] = { 0,1,2,0,1,2 };
uint32_t x = 1234567; // number to divide, and remainder at the end
uint32_t y = 0; // result
int bit = 31; // current bit
printf("X=%u X/3=%u\n",x,x/3); // the '/3' is for testing
while (bit>0)
{
printf("BIT=%d X=%u Y=%u\n",bit,x,y);
// decrement bit
int h = 1; while (1) { bit ^= h; if ( bit&h ) h <<= 1; else break; }
uint32_t r = x>>bit; // current remainder in 0..5
x ^= r<<bit; // remove R bits from X
if (r >= 3) y |= 1<<bit; // new output bit
x |= mod3[r]<<bit; // new remainder inserted in X
}
printf("Y=%u\n",y);
}
Write the program in Pascal and use the DIV operator.
Since the question is tagged c, you can probably write a function in Pascal and call it from your C program; the method for doing so is system-specific.
But here's an example that works on my Ubuntu system with the Free Pascal fp-compiler package installed. (I'm doing this out of sheer misplaced stubbornness; I make no claim that this is useful.)
divide_by_3.pas :
unit Divide_By_3;
interface
function div_by_3(n: integer): integer; cdecl; export;
implementation
function div_by_3(n: integer): integer; cdecl;
begin
div_by_3 := n div 3;
end;
end.
main.c :
#include <stdio.h>
#include <stdlib.h>
extern int div_by_3(int n);
int main(void) {
int n;
fputs("Enter a number: ", stdout);
fflush(stdout);
scanf("%d", &n);
printf("%d / 3 = %d\n", n, div_by_3(n));
return 0;
}
To build:
fpc divide_by_3.pas && gcc divide_by_3.o main.c -o main
Sample execution:
$ ./main
Enter a number: 100
100 / 3 = 33
int div3(int x)
{
int reminder = abs(x);
int result = 0;
while(reminder >= 3)
{
result++;
reminder--;
reminder--;
reminder--;
}
return result;
}
Didn't cross-check if this answer is already published. If the program need to be extended to floating numbers, the numbers can be multiplied by 10*number of precision needed and then the following code can be again applied.
#include <stdio.h>
int main()
{
int aNumber = 500;
int gResult = 0;
int aLoop = 0;
int i = 0;
for(i = 0; i < aNumber; i++)
{
if(aLoop == 3)
{
gResult++;
aLoop = 0;
}
aLoop++;
}
printf("Reulst of %d / 3 = %d", aNumber, gResult);
return 0;
}
This should work for any divisor, not only three. Currently only for unsigned, but extending it to signed should not be that difficult.
#include <stdio.h>
unsigned sub(unsigned two, unsigned one);
unsigned bitdiv(unsigned top, unsigned bot);
unsigned sub(unsigned two, unsigned one)
{
unsigned bor;
bor = one;
do {
one = ~two & bor;
two ^= bor;
bor = one<<1;
} while (one);
return two;
}
unsigned bitdiv(unsigned top, unsigned bot)
{
unsigned result, shift;
if (!bot || top < bot) return 0;
for(shift=1;top >= (bot<<=1); shift++) {;}
bot >>= 1;
for (result=0; shift--; bot >>= 1 ) {
result <<=1;
if (top >= bot) {
top = sub(top,bot);
result |= 1;
}
}
return result;
}
int main(void)
{
unsigned arg,val;
for (arg=2; arg < 40; arg++) {
val = bitdiv(arg,3);
printf("Arg=%u Val=%u\n", arg, val);
}
return 0;
}
Would it be cheating to use the / operator "behind the scenes" by using eval and string concatenation?
For example, in Javacript, you can do
function div3 (n) {
var div = String.fromCharCode(47);
return eval([n, div, 3].join(""));
}
First that I've come up with.
irb(main):101:0> div3 = -> n { s = '%0' + n.to_s + 's'; (s % '').gsub(' ', ' ').size }
=> #<Proc:0x0000000205ae90#(irb):101 (lambda)>
irb(main):102:0> div3[12]
=> 4
irb(main):103:0> div3[666]
=> 222
EDIT: Sorry, I didn't notice the tag C. But you can use the idea about string formatting, I guess...
Using BC Math in PHP:
<?php
$a = 12345;
$b = bcdiv($a, 3);
?>
MySQL (it's an interview from Oracle)
> SELECT 12345 DIV 3;
Pascal:
a:= 12345;
b:= a div 3;
x86-64 assembly language:
mov r8, 3
xor rdx, rdx
mov rax, 12345
idiv r8
The following script generates a C program that solves the problem without using the operators * / + - %:
#!/usr/bin/env python3
print('''#include <stdint.h>
#include <stdio.h>
const int32_t div_by_3(const int32_t input)
{
''')
for i in range(-2**31, 2**31):
print(' if(input == %d) return %d;' % (i, i / 3))
print(r'''
return 42; // impossible
}
int main()
{
const int32_t number = 8;
printf("%d / 3 = %d\n", number, div_by_3(number));
}
''')
Using Hacker's Delight Magic number calculator
int divideByThree(int num)
{
return (fma(num, 1431655766, 0) >> 32);
}
Where fma is a standard library function defined in math.h header.
How about this approach (c#)?
private int dividedBy3(int n) {
List<Object> a = new Object[n].ToList();
List<Object> b = new List<object>();
while (a.Count > 2) {
a.RemoveRange(0, 3);
b.Add(new Object());
}
return b.Count;
}
I think the right answer is:
Why would I not use a basic operator to do a basic operation?
Solution using fma() library function, works for any positive number:
#include <stdio.h>
#include <math.h>
int main()
{
int number = 8;//Any +ve no.
int temp = 3, result = 0;
while(temp <= number){
temp = fma(temp, 1, 3); //fma(a, b, c) is a library function and returns (a*b) + c.
result = fma(result, 1, 1);
}
printf("\n\n%d divided by 3 = %d\n", number, result);
}
See my another answer.
First:
x/3 = (x/4) / (1-1/4)
Then figure out how to solve x/(1 - y):
x/(1-1/y)
= x * (1+y) / (1-y^2)
= x * (1+y) * (1+y^2) / (1-y^4)
= ...
= x * (1+y) * (1+y^2) * (1+y^4) * ... * (1+y^(2^i)) / (1-y^(2^(i+i))
= x * (1+y) * (1+y^2) * (1+y^4) * ... * (1+y^(2^i))
with y = 1/4:
int div3(int x) {
x <<= 6; // need more precise
x += x>>2; // x = x * (1+(1/2)^2)
x += x>>4; // x = x * (1+(1/2)^4)
x += x>>8; // x = x * (1+(1/2)^8)
x += x>>16; // x = x * (1+(1/2)^16)
return (x+1)>>8; // as (1-(1/2)^32) very near 1,
// we plus 1 instead of div (1-(1/2)^32)
}
Although it uses +, but somebody already implements add by bitwise op.
Use cblas, included as part of OS X's Accelerate framework.
[02:31:59] [william#relativity ~]$ cat div3.c
#import <stdio.h>
#import <Accelerate/Accelerate.h>
int main() {
float multiplicand = 123456.0;
float multiplier = 0.333333;
printf("%f * %f == ", multiplicand, multiplier);
cblas_sscal(1, multiplier, &multiplicand, 1);
printf("%f\n", multiplicand);
}
[02:32:07] [william#relativity ~]$ clang div3.c -framework Accelerate -o div3 && ./div3
123456.000000 * 0.333333 == 41151.957031
Generally, a solution to this would be:
log(pow(exp(numerator),pow(denominator,-1)))
Okay I think we all agree that this isn't a real world problem. So just for fun, here's how to do it with Ada and multithreading:
with Ada.Text_IO;
procedure Divide_By_3 is
protected type Divisor_Type is
entry Poke;
entry Finish;
private
entry Release;
entry Stop_Emptying;
Emptying : Boolean := False;
end Divisor_Type;
protected type Collector_Type is
entry Poke;
entry Finish;
private
Emptying : Boolean := False;
end Collector_Type;
task type Input is
end Input;
task type Output is
end Output;
protected body Divisor_Type is
entry Poke when not Emptying and Stop_Emptying'Count = 0 is
begin
requeue Release;
end Poke;
entry Release when Release'Count >= 3 or Emptying is
New_Output : access Output;
begin
if not Emptying then
New_Output := new Output;
Emptying := True;
requeue Stop_Emptying;
end if;
end Release;
entry Stop_Emptying when Release'Count = 0 is
begin
Emptying := False;
end Stop_Emptying;
entry Finish when Poke'Count = 0 and Release'Count < 3 is
begin
Emptying := True;
requeue Stop_Emptying;
end Finish;
end Divisor_Type;
protected body Collector_Type is
entry Poke when Emptying is
begin
null;
end Poke;
entry Finish when True is
begin
Ada.Text_IO.Put_Line (Poke'Count'Img);
Emptying := True;
end Finish;
end Collector_Type;
Collector : Collector_Type;
Divisor : Divisor_Type;
task body Input is
begin
Divisor.Poke;
end Input;
task body Output is
begin
Collector.Poke;
end Output;
Cur_Input : access Input;
-- Input value:
Number : Integer := 18;
begin
for I in 1 .. Number loop
Cur_Input := new Input;
end loop;
Divisor.Finish;
Collector.Finish;
end Divide_By_3;

Resources