從前 NN 個自然數中可能的兩組數字和差為 DD,用 C++ 程式設計
在這個問題中,我們有兩個整數 N 和 D。我們的任務是檢查是否可以從前 NN 個自然數集合中得到兩組數字之差為 D。
我們舉個例子來理解這個問題,
輸入 − N=5 D =3
輸出 − 是
解釋 −
Out of 1, 2, 3, 4, 5.
We can have two sets set1= {1, 2, 3} and set2 = {4, 5}, this will give difference 3.
{4+5} - {1+2+3} = 9- 6 = 3為了解決這個問題,我們將進行一些數學計算。
我們知道,所有數字之和等同於兩個集合元素之和,
所有 n 個自然數的和的公式,
sum(s1) + sum(s2) = (n*(n+1))/2. Given in the problem, sum(s1) - sum(s2) = D
將兩者相加得到,
2*sum(s1) = ((n*(n+1))/2) + D
如果此條件成立,那麼只能找到一種解決方案。
示例
展示如何實現我們解決方案的程式,
#include <iostream>
using namespace std;
bool isSetPossible(int N, int D) {
int set = (N * (N + 1)) / 2 + D;
return (set % 2 == 0);
}
int main() {
int N = 10;
int D = 7;
cout<<"Creating two set from first "<<N<<" natural number with difference "<<D<<" is ";
isSetPossible(N, D)?cout<<"possible":cout<<"not possible";
return 0;
}輸出
Creating two set from first 10 natural number with difference 7 is possible
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP