Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับวิธีแสดงจำนวนเป็นผลรวมจำนวนต่อเนื่องด้วย C++

ได้รับจำนวนเต็ม n เป็นอินพุต เป้าหมายคือหาจำนวนวิธีที่เราสามารถแสดง 'num' เป็นผลรวมของจำนวนธรรมชาติที่ต่อเนื่องกันสองตัวขึ้นไป ตัวอย่างเช่น ถ้า n=3 สามารถแสดงเป็นผลรวม (1+2) ได้ รวม 1 วิธี

ตัวอย่าง

Input

num=6

Output

Count of ways to express a number as sum of consecutive numbers are: 1

Explanation

The ways in which we can express 'num' as sum of consecutive natural numbers: 1+2+3

Input

num=19

Output

Count of ways to express a number as sum of consecutive numbers are: 1

Explanation

The ways in which we can express 'num' as sum of consecutive natural numbers: 9+10

วิธีการที่ใช้ในโปรแกรม

วิธีนี้แสดงจำนวนเป็นผลรวมของ (a + a+1 + a+2...+ a+i) ซึ่งกลายเป็น a*(i+1) + 1+2+3+...+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

  • รับจำนวนเต็ม num เป็นอินพุต
  • ฟังก์ชัน sum_consecutive(int num) คืนค่าจำนวนวิธีแสดงเป็นผลรวมจำนวนต่อเนื่อง
  • กำหนดจำนวนนับเริ่มต้นเป็น 0
  • ตัวแปรชั่วคราว res ชนิด float
  • ลูป for จาก i=1 ถึง i*(i+1)/2 < num
  • คำนวณค่า [ num - (i)*(i+1)/2 ] / (i+1) เก็บใน res
  • ถ้า res เป็นจำนวนเต็ม (res - (int)res == 0) เพิ่ม count
  • คืนค่า count เป็นผลลัพธ์

ตัวอย่างโค้ด

#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;
}

Output

หากรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

Count of ways to express a number as sum of consecutive numbers are: 1