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

ผลรวมของสองตัวเลขแบบโมดูล로 M ใน C++


ภาพรวมปัญหา

ได้รับตัวเลข 3 ตัวคือ a, b, และ M หาผลรวมของ a และ b แล้วหาเศษเมื่อหารด้วย M

ตัวอย่าง

Input: a = 14, b = 54, m = 7
Output: 5
Explanation: 14 + 54 = 68, 68 % 7 = 5

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

#include <iostream>
using namespace std;

int moduloSum(int a, int b, int M) {
    return (a + b) % M;
}

int main() {
    int a = 35, b = 12, M = 7;
    cout << "The sum modulo is " << moduloSum(a, b, M);
    return 0;
}

ผลลัพธ์

The sum modulo is 5