ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
dose anyone know who to write loop to raise power using +/- operator only?
(eg: 2^3 = 8, 7^2 = 49, 5^4 = 625, 15^7 = 170859375 and so on)
thanks in advance
Another one of those homework assignments, I suppose :P I will tell you without the solution :P 2^3=8 could be writen 2+2+2+2=8 and like. Try to figure this out on your own.
int result = 0;
//loop to calculate the multiply() method
for(int i = 1; i <= secondNumber; i++)
{
result += firstNumber;
}
System.out.println("The result is: "+ result);
//usage <filename> x y where you want x^y
int main(int argc, char *argv[])
{
int answer;
answer = function add_power(argv[0], argv[1]);
printf("%d to the power %d is %d\n", argv[0], argv[1], answer);
return 0;
}
int add_power(x, y)
{
int i;
int retval;
if(y == 1)
{
return x;
}
else
{
for(i = 0; i < x; i++)
{
retval += add_power(x, y-1)
}
return retval;
}
}
The recursive function might need a little tweaking (I only spent a minute on this) but that's the basic idea.
Actually, I felt a bit bad about posting that since you did say that it would require some tweaking. Didn't notice that until after I posted, and then I felt like I was nitpicking...
I can see at least a few other things that would need to be tweaked, but it would probably be better to leave it up to the original poster to figure those things out...
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.