กำหนดจำนวนเต็ม n เป็นอินพุต เป้าหมายคือการหาจำนวนวิธีที่เราสามารถแสดง 'num' เป็นผลรวมของตัวเลขธรรมชาติสองตัวหรือมากกว่าที่ต่อเนื่องกัน ตัวอย่างเช่น ถ้า n เป็น 3 สามารถแสดงเป็นผลรวม ( 1+2 ) ได้ทั้งหมด 1 วิธี
ตัวอย่าง
อินพุต
num=6
ผลลัพธ์
Count of ways to express a number as sum of consecutive numbers are: 1
คำอธิบาย
The ways in which we can express ‘num’ as sum of consecutive natural numbers: 1+2+3
อินพุต
num=19
ผลลัพธ์
Count of ways to express a number as sum of consecutive numbers are: 1
คำอธิบาย
The ways in which we can express ‘num’ as sum of consecutive natural numbers: 9+10
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในวิธีนี้เราจะแสดงตัวเลขเป็นผลรวมของ ( a + a+1 + a+2…..+ a+i )
ซึ่งจะกลายเป็น (a)(L+1) คูณ + 1+2+3+4…+i =a*(i+1) + i*(i+1)/2 (ผลรวมของจำนวนธรรมชาติ i) num=a*(i+1) + i*(i+1)/2.a=[ num − (i)*(i+1)/2 ] / (i+1)
เราจะทำสิ่งนี้สำหรับ i=1 ถึง i*(i+1)/2 น้อยกว่า num
-
ใช้จำนวนเต็มเป็นอินพุต
-
ฟังก์ชัน sum_consecutive(int num) ใช้ num และคืนค่าจำนวนวิธีที่จะแสดง 'num' เป็นผลรวมของจำนวนธรรมชาติที่ต่อเนื่องกัน
-
นับเริ่มต้นเป็น 0
-
ใช้ความละเอียดของตัวแปรชั่วคราวเป็นแบบลอย
-
ใช้สำหรับวนรอบจาก i=1 ถึง i*(i+1)/2
-
คำนวณค่า [ num − (i)*(i+1)/2 ] / (i+1) และเก็บในรูปแบบ res.
-
หาก res เป็นจำนวนเต็ม ( res − (int)res คือ 0 ) ให้นับจำนวนที่เพิ่มขึ้น
-
ในตอนท้ายเราได้นับเป็นวิธีที่สามารถแสดง num เป็นผลรวมของจำนวนธรรมชาติที่ต่อเนื่องกัน
-
ผลตอบแทนนับเป็นผลลัพธ์
ตัวอย่าง
#include <bits/stdc++.h> using namespace std; int sum_consecutive(int num){ int count = 0; int temp = num * 2; float res; for (int i = 1; i * (i + 1) < temp; i++){ int store = i + 1; res = (1.0 * num−(i * (i + 1)) / 2) / store; float check = res − (int)res; if(check == 0.0){ count++; } } return count; } int main(){ int num = 20; cout<<"Count of ways to express a number as sum of consecutive numbers are: "<<sum_consecutive(num) << endl; return 0; }
ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count of ways to express a number as sum of consecutive numbers are: 1