[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
Hi /g/ I got a problem: I have to make a program in C that can
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 121
Thread images: 12
File: help us obi wan.jpg (34 KB, 500x471) Image search: [Google]
help us obi wan.jpg
34 KB, 500x471
Hi /g/ I got a problem:
I have to make a program in C that can raise a number to a power without using pow function. I mean, raise x to a power y, where x its a real number and y is an integer number.
>>
>>54094553
what the FUCK is a power?
>>
File: exponents.jpg (27 KB, 553x484) Image search: [Google]
exponents.jpg
27 KB, 553x484
>>54094577
You know, man: Exponents
>>
>>54094553
>not trying to understand the maths behind the problem
If you bothered to understand what a power does, you'd see this is trivial.
This is what sets the CS folk apart from node.js meme coders, and it's why you'll be first to list your job when the bubble bursts, just like last time
>>
>>54094700
>If you bothered to understand what a power does, you'd see this is trivial.
If you find this to be trivial you either have no idea or you take having heard of this algorithm for granted
>>
>>54094724
This really is trivial. I'm pretty sure most computer scientists would consider implementing quicksort or mergesort trivial, and this is quite a bit simpler than either of those.
>>
>>54094700
Yeah, you attempt to explain anything makes me sick. Fuck you, and fuck off /g/
>>
Don't you just multiply a number by itself X times?
For example 2^4 = 2*2*2*2
Isn't this middle school-tier math?
>>
>>54094724
If you get into 2nd year CS and can't do that off the top of your head, wuit now and save yourself the embarrassment.

Fucking CEng here, couldn't get floats that were stored in uint_32 to be properly casted, so I wrote a function that did that myself. If I could do that with nothing but a java webapp that demoed binary to IEEE754, you can make your own damn pow() function
>>
>>54095140
>Don't you just multiply a number by itself X times?
>For example 2^4 = 2*2*2*2
>Isn't this middle school-tier math?
If your middle school starts around grade 5 or 6, yes.

Seriously OP, this is trivial shit.
>>
>>54094553
How can you aspire to be a computer programmer if mundane arithmetic eludes you?
>>
>>54094553
You should really consider dropping out if you can't even wrap your head around something this simple.
>>
Am I missing something here? This seems like baby math...

Enter a value X.
Enter a value Y.

While Y isn't 1, multiply X*X and reduce Y by 1.

If you're feeling fancy, first check if Y is 0 and if it is return 1.
>>
>>54094553
>>54094724
It's trivial as fuck, how did you graduate high school without knowing how this shit works
>>
Seriously OP, I'm in CS too and I'm worried that I might not be good enough at math to succeed, but even this is pretty straightforward. If you don't even know how to convert the mathematical rules for taking the power of a number into something a computer can understand, you're really going to struggle when you have to calculate complexity of various algorithms and stuff. This is pretty much middle school math, not even calculus or trig or anything like that.
>>
Im not on CS, thats the fucking problem! If im had to do it in paper, it would be easy stuff, too fucking easy but my teacher wants in C, in fortran its easyer. Im aspiring to be mathematician not a fucking geek.
>>
>>54095426
So you have experience in Fortran? Do you know how to do loops in C? If not, it's fairly easy to look up online. Or are you actually having problems with another aspect of implementing it in C?
>>
File: 1456076492894.gif (479 KB, 500x281) Image search: [Google]
1456076492894.gif
479 KB, 500x281
float exponent(float x, float y){
float exp = x^y;
return exp;
}
>>
>>54094553
welcome to like grade 7 mathematics.
>>
That should take you a minute, tops. If you can't do that without help you need to change your major right this instant.
>>
>>54095237
I'd use a for rather than while, but yeah: super trivial, OP is a babby
>>
>>54095426
>Im aspiring to be mathematician
>Can't write about basic logic statements
Quit now.
>>
>>54095545
Lol in c that's the bitwise xor operator, nice try though.
>>
>>54095598
>without using pow function

>>54095600
While is simpler. And internally, aren't for loops actually implemented as while loops. As in
for (int i = 0; i < 10; i++) {
//do something
}


is really internally handled as
int i = 0;
while (i < 10) {
//do something
i++;
}
>>
>>54094700
Seriously how does someone not understand this, I'm not a programmer, am an engineer, this is like junior high maths
>>
>>54095662
Yeah but for loop is better because the iterator is local to the loop.
>>
>>54094553
Do your own homework.
>>
>>54095695
oh right..
how would you raise a number to an irrational power?
>>
>>54095779
You don't need to, it's specified that the power is an integer.
>>
>>54095779
oh.. wait.. OP just wants to work with integers?

sorry..

>>54095695
OP is indeed a fag
>>
>>54095799
Right, i realized my mistake, but..
how would you?
>>
>>54095662
dude are you fucking seriously doing this in linear time?
>>
>>54095662
Thanks, man. I tried something like this and nope:
#include <stdio.h>
Int main ()
{
float x, y;
int n;
printf ("enter the base: \n");
scanf ("%f", &x);
printf ("enter the exponent: \n");
scanf ("%d", &n);
y= x**n
printf ("your number is: \n"
"y= %f.\n");
return 0;
}
But in spanish the prints xD I'm from Mexico and until now i dont acquaired with math terminology, cuz until the grade im the books r in spanish, in the next ones are in english. However I thank u.
>>
File: 1432849347971.jpg (164 KB, 508x610) Image search: [Google]
1432849347971.jpg
164 KB, 508x610
>>54094553
shift the bit meng
>>
Why everybody thinks that its an arithmetic problem? Its self- explanatory that its a computer problem, a programming problem.
>>
>>54095896
Your program is braindead.

using
>y=x**n
Is exactly the same as using pow(x, n)

Do you not understand what you're being asked to do?
Please think b4 u cumpile

PS. semicolon..
also work on your english.
Most people will tell you to fuck off when it's so obvious that you haven't put in effort to think through a problem. So next time think and check yourself.
>>
>>54094553

>the "simple" way
const unsigned precision=40;
double exponential(unsigned n, double x) //exp(x)
{
double sum = 1.0;

for (int i = n - 1; i > 0; --i ){
sum = 1+x*sum/i;
}

return sum;
}

double log_natural_frac(unsigned n, double x){ //ln(1-x) & |x|<1
double sum=0;
for(int i=n-1;i>0;--i){
sum*=x;
sum+=x/i;
}
return -sum;
}

double log_natural(unsigned n, double x){
double e=exponential(n, 1), log=0;
int power=1;
double ePow=e;
while(ePow<x){
ePow*=e;
power<<=1;
}
ePow/=e;
power>>=1;
while(power>0){
if(ePow<x){
x/=ePow;
log+=power;
}
ePow/=e;
power>>=1;
}
if(x>1){
x/=e;
++log;
}

return log+log_natural_frac(n,1-x);
}

double power(double b, unsigned long long n){
double result=1, bPow=b;
while(n){
if(n&1){
result*=bPow;
}
bPow*=bPow;
n>>=1;
}
return result;
}

double power(double b, double e){
if(e<0){
return 1/power(b,-e);
}
double result=power(b, static_cast<unsigned long long>(e));
e-=static_cast<unsigned long long>(e);
if(e==0){
return result;
}
return result*exponential(precision, e*log_natural(precision, b));
}
>>
>>54095716
in this case, it doesn't matter.
>>
>>54095995
I'm pretty sure that most people would take this like an offensive stuff, but really its constructive. Thanks, brah.
>>
>>54094553
While count < y:
x = x*x
count += 1


there
>>
>>54094836
Computer scientist here and quicksort is nontrivial due to the choice of the pivot being both very open-ended and very important.
>>
>>54095237
>While Y isn't 1, multiply X*X and reduce Y by 1.
This implements
X^(2^Y)
>>
>>54096206
This also implements
X^(2^Y)
.

I never realized how great of an interview algorithm this ridiculously simple problem is. 99% of non-programmers fail it.
>>
File: merge sort.png (11 KB, 1294x108) Image search: [Google]
merge sort.png
11 KB, 1294x108
>>54094836
>I'm pretty sure most computer scientists would consider implementing quicksort or mergesort trivial
>>
File: image.jpg (19 KB, 190x254) Image search: [Google]
image.jpg
19 KB, 190x254
>>54094553
I suggest this
>>
>>54096297
My solution works right?
>>
>>54094836
The solution that has a runtime linear to the exponent is not acceptable, mind you
>>
>>54094553
float x, z;
int y;
scanf("%f", &x);
scanf("%d", &y);
x = z;
while (y --> 1)
x *= z;
printf("%f", x);
return 0;


I'll leave it to you to find the right library to use the arrow operator in the while loop OP.
>>
>>54095237
>>54095600
>>54095695
>>54096206
>>54096415
Complete retards

>>54096019
Mah floating point nigga

No one's mentioned the binary factorization method which is clearly the answer OP is looking for
>>
>>54096302
He said implementing retard. Coming up with something and knowing something enough to make a working implementation are two different things.
>>
>>54096958

Any retard could brain storm up merge sort.
>>
>>54095140
You can make it more efficient than that, but essentially yes.
>>
>>54096443
>binary factorization

Not OP but new to g and programing
I know OP should have just looped (x*x) for (y-1) number of times, (special case for 0 obviously) but what exactly is binary factorization?
>>
>>54097784
Just a shitposter trying to claim he's smart. The only references I can find are for binary matrix factorization, which is definitely not what op is doing.
>>
>>54097864
Ok, thanks anon
>>
>>54097891
What he probably means is that you can calculate x^y in O(sqrt(y)) instead of O(y) like everyone is doing. Am in class now, might post the algo later if thread is still up.
>>
>>54098587
I'm dumb, it's actually O(log y)
>>
>>54098619
ah, I think I get it
>>
>>54094553

Some years ago:
>OP: "guyz, help me coding"
>"not doing your homework!"
>"fuck off, OP!"
>"do you even google?"

Nowadays:
>OP: "guyz, help me coding"
>"of course anon, let me spoonfeed you!"
>"here OP, I made a second version for you, do you like it?"
>"OP, here is a third version, is it kawaii enough for you?"

Disgusting.
>>
>>54094553
I hope you fail. We need to stop letting these guys pass by put technology behind a few years each time.
Don't know how to multiply something in a loop? Please go make burgers or something.
>>
>>54098659
validation desperate millenials senpai
>>
>>54094553
...multiply x times itself y times
>>
>>54098659
We should have stopped somewhere in the middle.
>>
>>54095779
Ummm... highschool level maths?
x^y = exp( log( x^y ) ) = exp( y * log( x ) )
exp() is trivial to implement (Taylor series), log() is not but it's not rocket science either.
>>
File: 1443669082458.png (71 KB, 369x406) Image search: [Google]
1443669082458.png
71 KB, 369x406
ITT:
>>
>>54096372
If you were >>54096206 or >>54095237 then it does not.
>>
>>54099049
int power(int x, int y) {
for(int i = 0; i < y; i++){
x = x * x;
}
}

FUCK YOU OP RETARD
>>
>>54095662
In the end they all effectively result in:
int i = 0;
pos:
if (i < 10) {
// do things
i++;
goto pos;
}
>>
>>54101205
But that's wrong
>>
File: images-12.jpg (25 KB, 382x385) Image search: [Google]
images-12.jpg
25 KB, 382x385
What a bunch of fucking hillbillies! 5, 6,7 grade? In my contry its for retards get to 3 grade whitout know exponents. Well done, americans you did it again.
>>
>>54101227
That doesnt run on gcc, fucking dweeb
>>
File: god bless.jpg (389 KB, 1368x912) Image search: [Google]
god bless.jpg
389 KB, 1368x912
>>54101832
yeah but you're still afraid of inanimate objects well into adulthood.
>>
>everyone is implementing it in linear time
THIS IS WHY YOU READ SICP KIDS
>>
>>54101975
Works on my machine!
>>
File: images-28.jpg (16 KB, 378x389) Image search: [Google]
images-28.jpg
16 KB, 378x389
>>54102118
Oh, yeah! Was my mistake, sorry.
>>
>>54102049
Hahaha a bunch of bellicose monkeys!
>>
>>54097784
He's talking about repeated squaring. It's what >>54096019 is doing for "double power(double b, unsigned long long n)"
>>
static void _power( double *result, const double x, const int n )
{
*result*=(n?x:1);
n?_power(result,x,n-1):0;
}

double power( const double x, const int n )
{
double result = 1;
_power( &result, x, n );
return result;
}
>>
{-# LANGUAGE BangPatterns #-}

import Test.QuickCheck
import Criterion.Main

powSlow, powFast :: (Num a, Integral b) => a -> b -> a

powSlow _ 0 = 1
powSlow x n = x * powSlow x (n-1)

powFast _ 0 = 1
powFast !x n = x' * powFast (x*x) n'
where (n',r) = n `quotRem` 2
x' = case r of 0 -> 1; 1 -> x

-- Tests

test :: (Int -> Int -> Int) -> Int -> Int -> Property
test f x y = (y >= 0) ==> (f x y == x^y)

propPowSlow = test powSlow
propPowFast = test powFast

-- Benchmarks

benchmark = defaultMain [ bench "slow" $ whnf (powSlow 123456) 123456,
bench "fast" $ whnf (powFast 123456) 123456 ]

main = do quickCheck propPowSlow
quickCheck propPowFast
benchmark


λ ghc -O2 pow.hs -o /tmp/pow && /tmp/pow
[1 of 1] Compiling Main ( pow.hs, pow.o )
Linking /tmp/pow ...
+++ OK, passed 100 tests.
+++ OK, passed 100 tests.
benchmarking slow
time 1.976 s (1.950 s .. 1.992 s)
1.000 R2 (1.000 R2 .. 1.000 R2)
mean 1.962 s (1.952 s .. 1.968 s)
std dev 9.093 ms (0.0 s .. 10.04 ms)
variance introduced by outliers: 19% (moderately inflated)

benchmarking fast
time 17.06 ms (17.02 ms .. 17.10 ms)
1.000 R2 (1.000 R2 .. 1.000 R2)
mean 17.10 ms (17.07 ms .. 17.18 ms)
std dev 104.3 μs (47.64 μs .. 201.1 μs)
>>
>>54095175

What about negative, fractional or irrational powers?
>>
>>54098587
>>54098627
Took me a bit to get it right as an iteration, the recursion is much prettier.
double power(const double x, int y) {
if (y < 0) return 1 / power(x, -y);
double buffer = x;
double result = 1;
int exponent = y;
while (exponent > 0) {
if (exponent % 2) {
result *= buffer; //x^{y+1} = x * x^y
--exponent;
} else {
buffer *= buffer; //x^y = x^{y*2/2} = (x^2)^{y/2}
exponent /= 2;
}
}
return result;
}
>>
>>54095140
>Don't you just multiply a number by itself X times?

Do you add a number Y by itself X times to do Y*X? Do you increment a number Y X times to do Y+X? Stop being retarded.
>>
>>54104508
>What about negative, fractional or irrational powers?
>>54094553
>where x its a real number and y is an integer number.

That gives room for negative, but I assume he meant unsigned positive integer
>>
File: CS.png (4 KB, 224x250) Image search: [Google]
CS.png
4 KB, 224x250
>>54095198
Because if mundane arithmetic eludes you, you aspire to be a computer programmer.
>>
>>54104508
>What about negative powers

You did not just seriously ask that
>>
>>54104722
>Do you increment a number Y X times to do Y+X?
This is accurate though
>>
>>54094553
This is not tecnology.
If you're so dumb that you can do this, you better think of leaving STEM
>>
>>54094553
Since you only have integer powers, this is really, REALLY fucking easy holy shit. git good senpai
>>
>>54104508
Negative powers, easy as fuck. If it's negative, just divide and increment instead of multiply and decrement.
>>
>>54104722
Some operations are supported by the hardware, some aren't, faggot. Come back when you find the power instruction in x86 asm.
>>
>>54094553
Is this not just a while loop that multiplies the number itself a number of times that is equal to the power you want to raise the number to minus 1? Am I missing something. Why does this thread have 89 replies?
>>
>>54105199
number by itself*
>>
>>54104906

It's exponential in X (X's bits)

>>54105119
>Some operations are supported by the hardware, some aren't, faggot. Come back when you find the power instruction in x86 asm.

It's literally the same algorithm in all three cases. Did you fail first grade math

double power(double x, unsigned long long y){
double result=1, xPow=x;
while(y){
if(y&1){
result*=xPow;
}
xPow*=xPow;
y>>=1;
}
return result;
}

double multiply(double x, unsigned long long y){
double result=0, xDup=x;
while(y){
if(y&1){
result+=xDup;
}
xDup<<=1; //or xDup+=xDup;
y>>=1;
}
return result;
}

double add(double x, unsigned long long y){
double result=x; unsigned long long twoPow=1, carry=0; bool nextcarry=0;
while(y){
if( (y&1) || carry){
nextcarry = (result & twoPow) | (twoPow & carry) | (result & carry);
result^=(twoPow^carry);
}
twoPow<<=1; // or twoPow+=twoPow;
y>>=1;
carry= nextcarry ? twoPow : 0;
}
return result;
}
>>
>>54095426
Of you can do it in Fortran you can do it in C. If you aspire to be a mathematician--you know what, fuck it. This is bait.
>>
>>54105411
>It's literally the same algorithm in all three cases. Did you fail first grade math
How dense are you? Of course I know that, but the CPU does addition for you, so you don't have to increment. It does multiplication for you, so you don't have to add. It doesn't do exponentiation, so you have to write it yourself or use a library. If you include exponentiation in your language, you still have to compile it to multiple multiplications. Clearer now, fuckface?
>>
>>54105839
>It doesn't do exponentiation
x86 basically does. (Two instructions, not one, but close enough)
>>
>>54105955
I wasn't aware of that. How would you do it?
>>
I...I think this is right...

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
int number;
int power;
int inc;
int result = 1;

printf("Enter a number: ");
scanf("%d", &number);
printf("\nEnter the power you want to raise the number to: ");
scanf("%d", &power);

for (inc = 1; inc <= (power); inc++)
{
result = result * number;
}

printf("\n%d^%d = %d\n\n", number, power, result);

system("pause");
return 0;
}
>>
>>54105994
x^y = (2^log2(x))^y = 2^(log2(x) * y)

x86 has an instruction for 2^x and an instruction for y * log2(x).
>>
>>54094553
try sqt
now fuck off
>>
>>54106175
18 hours too late, edgelord.
>>
x = 1,2.....
y=1,2.....
z= x^y
print z
op is a retard this is like 5th grade math and nothing to do with programming, i dont even remember how to code c.
end
>>
>>54106044
Is there now pow() function in math?
>>
if y is an integer, and x is a real, then you can trivially define a power function recursively as:

x * power(x, y-1) if y > 1
x if y = 1
1 if y = 0
1 / power(x, -y) if y < 0

Translating this into C code should be trivial, either with recursion or with a for loop. If you need better performance, you use the square and multiply algorithm (google it, it can be useful to know).
>>
>>54106290
yes, I included it because I meant to test answers with the function, but never did
>>
>>54106044
Get rid of the system("pause");

>>54106290
Yes, pow(double base, double exponent) has always been a part of the C standard library, at least since c89.
>>
>>54106333
other than the system("pause") is there anything else bad about it?
>>
Question for you guys how can one program an algorithm for x to the power y. Where y is a real number. Am I then using Taylor series?
>>
>>54106390
Not the tripfag, just a random anon here.
It's fine, it's pretty basic code after all. I'm pretty sure you don't need the stdlib and math includes.

As a matter of coding style, instead of your for loop, I would write it like
 for (inc = 0; inc < power; inc++)
{
result *= number;
}

or even
 for (inc = 0; inc < power; inc++) result *= number;


Nothing wrong with the way you did, though, just a matter of convention.
>>
>>54106044
now do it in less than linear time
>>
>>54106474
yes you need e for that
>>
>>54097005
Really? So I guess that means you won't need to look it up on stackexchange next time you're told to implement mergesort for an interview.
>>
>>54106474
see >>54096019
>>
>>54106536
lmao
>>
Is it really not clear? You make a loop execute the number of times that someone inputs as the exponent. Then you're not using a power function.
>>
>>54106305
>x if y = 1
redundant unless you really care about your stupid 0^0 being 0
>>
>>54095140
What about negative powers bro
>>
File: Youre_under_arrest.webm (2 MB, 1280x720) Image search: [Google]
Youre_under_arrest.webm
2 MB, 1280x720
>>54095984
One in the same senpai.

OP this is actually pretty trivial. And I'm not even good at programming.

Advice - whenever you are stuck on something like this, break out some paper and a pencil. This is applicable on nearly all levels of coding. Smaller levels, you can write out pseudo code or Algos on a piece. Large projects it is still helpful, you just have to section it off and be general about it.

So, write out some steps to raise things to a power.

3^2 is 3 times 3
5^4 is 5 times 5 times 5 times 5. Or 5 multiple by 5 n times.

Now think really hard if only we had a way to make a program do something while a condition isn't met. We could keep multiplying a number by m, and store it in a variable, and then do the same with that number. And think if ONLY we had a way to keep track of some variable to let us know what iteration of that thing I talked about earlier to stop it. Weird, maybe python has it but CERTAINLY not C.

Anyways, that's how I would do it. Is there an easier way? Maybe but that's what came to me as I sit here at BK. If this is foreign to you, then you are never gonna make it senpai.
>>
>>54094724
You fucking retard, write a for loop that multiplies x by itself y times its not fucking rocket science
>>
>>54104790
Philosophical tier shit
>>
>>54106955
what's funny
Thread replies: 121
Thread images: 12

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.