Inspired by joj 2042: a method for writing a program to calculate Power Function

Source: Internet
Author: User

JOJ 2042 is a program comprehension question, which provides a wonderful program for calculating x ^ 3. The principle is as follows:

It can be seen from the above that the power function increases by 6 for the first time, and its initial value is 1. Therefore, you can write the program to calculate the Cube as follows:

Int f (x ){

Int c = 0, d = 1, e = 6;

While (x --){

C + = d;

D + = e;

E + = 6;

}

Reutnrn c;

}

Similarly, based on this idea, you can write similar programs for square calculation:

X2-(x-1) 2 = 2 * X-1, the addition of the square function, the initial value is 1

2 * X-1-[2 * (x-1)-1] = 2, the increase of the square function, is constant 2

So the following program can calculate the square of the input positive integer:

# Include <stdio. h> </P> <p> int F (int x) {<br/> int C = 0, D = 1; <br/> while (X --) {<br/> C + = D; <br/> D + = 2; <br/>}< br/> return C; <br/>}</P> <p> int main () {<br/> int N; <br/> while (scanf ("% d ", & N), n) {<br/> printf ("% d/N", F (n); <br/>}< br/> return 0; <br/>}</P> <p>

There is a formula for this factorization: An-BN = (a-B) (An-1 + an-2b +... + Abn-2 + bn-1), theoretically should be able to calculate.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.