[ 3 / biz / cgl / ck / diy / fa / ic / jp / lit / sci / vr / vt ] [ index / top / reports ] [ become a patron ] [ status ]
2023-11: Warosu is now out of extended maintenance.

/sci/ - Science & Math


View post   

File: 75 KB, 500x376, 1339007434387.jpg [View same] [iqdb] [saucenao] [google]
5193640 No.5193640 [Reply] [Original]

How would one go about creating a modulus function in a programming language where you can only use addition, subtraction, multiplication, and division?

I can think of one way (I'll be writing this in C-like code)
to calculate 8436 % 10:

int a = 8436; // declare integer value a
int b = a / 10; // b = 843 (integer division)
b = b * 10; // b = 8430
int c = a - b; // c = 8436 % 10 = 6

Are there any more efficient ways of programming something like this?

>> No.5193663 [DELETED] 

>>5193640
if you're working with pure integers,

a - (b * (a/b))

should do it

>> No.5193674

inline X86 machine code
divide and get the second register holding the remainder.

>> No.5193675

>>5193640
believe C basically floors any result of integer division where the result is an integer, so you could basically just do (in a function)...

int mod = a - (b * (a/b))

something like that.