आसान 0 हल किए गए 0% स्वीकृति

Difference of Squares

Subtract the sum of squares from the square of the sum.

आप क्या सीखेंगे

  • Compute sums of numbers and of squares
  • Use closed formulas instead of loops
  • Compare two ways to get the same answer

समस्या

अनुवाद दिखाएँ

Using the integers from 1 through n, calculate two quantities: first add the integers and square the result; separately square each integer and add those squares. Return the first quantity minus the second.

Implement difference_of_squares(n).

Input

n: The last integer to include.

Output

Return square-of-sum minus sum-of-squares.

सीमाएँ

0 ≤ n ≤ 50,000. For n = 0, both sums are 0. All required values fit signed 64-bit integers.

उदाहरण

उदाहरण 1
इनपुट:
n = 4

अपेक्षित आउटपुट:
expected = 70
इनपुट:
long long n = 4;

अपेक्षित आउटपुट:
long long expected = 70;
इनपुट:
long n = 4;

अपेक्षित आउटपुट:
long expected = 70;

व्याख्या

(1 + 2 + 3 + 4)² = 100. The sum of squares is 1 + 4 + 9 + 16 = 30. Subtract: 100 − 30 = 70.

उदाहरण 2
इनपुट:
n = 1

अपेक्षित आउटपुट:
expected = 0
इनपुट:
long long n = 1;

अपेक्षित आउटपुट:
long long expected = 0;
इनपुट:
long n = 1;

अपेक्षित आउटपुट:
long expected = 0;

व्याख्या

Both quantities equal 1, so their difference is 0.

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

You are comparing two summaries of the same range: one based on summing first, the other based on squaring first.

संकेत 2

Use the closed-form expressions for sums of integers and sums of squares instead of looping through every value.

संकेत 3

Handle the zero case carefully, since both quantities should be zero there.

अपेक्षित जटिलता

O(1) time, O(1) extra space

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।