Hashbrowns
Hashbrowns

Reputation: 93

How can I make 5 mod 5 = 5 instead of zero?

I'm making a program that uses mod 5.

So I divide the input numbers by five and return the remainder.

var mod5 = function (xx) {
     var mod = 5;
     return ((xx % 5) + 5) % 5;
}

thus 6 = 1, 4 = 4, and 8 = 3.

By following this rule all things divisible by 5 = 0,

In order for my program to work, 5, 10, 15, 20 ... mod 5, all must = 5 instead of 0.

But all other numbers need to remain the same. What is the easiest way to do this?

P.S. I'm extremely new to programming and I'm sorry if this doesn't make sense.

Upvotes: 1

Views: 1422

Answers (5)

nigelhenry
nigelhenry

Reputation: 489

var mod_positive = var(xx, yy = 5){
    return ((xx - 1) %% yy) + 1;
}

This question is a repeat of this: How can I modulo when my numbers start from 1, not zero?

Upvotes: 0

Omar Vazquez
Omar Vazquez

Reputation: 407

var mod5 = function (xx) {
  return (xx % 5) || 5
}

This function will return xx mod 5 if it is different of zero, otherwise it will return 5, more explained:

xx % 5 will result in any number between -4 and 4 -4 <= xx % 5 <= 4, then, an OR logical operator compares that result with the number five, the OR logical operator works as the following:

If the value in the left side of the operator is true, or truthy it will be returned independently of the value in the right side.

If the value in the right side is true, or truthy, AND the value in the left side is false, or falsy it will be returned.

Orherwise, in case none of the value is true or truthy, false will be returned.

In this case, xx % 5 will be returned only if xx is not multiple of 5, otherwise, 5 will be returned.

Hope that helps :)

Upvotes: 6

rnd_keith
rnd_keith

Reputation: 31

Made the assumption that if 0 was passed in, you'd want 0 to come back instead of 5.

var mod5 = function(xx) {
    var mod = 5;
    if (!xx)
        return 0;
    if (xx % mod === 0)
        return mod;
    return xx % mod;
}

Upvotes: 0

Paul
Paul

Reputation: 36339

function mod5(x) {
  var result = x % 5; 
  if (result === 0) return 5;
  return result;
}

Per your requirements, anything that is divisible by 5 will yield 5. Everything else is unchanged.

Upvotes: 2

jdmdevdotnet
jdmdevdotnet

Reputation: 1

var mod5 = function (xx) {
    var mod = xx % 5;
    if(mod == 0) 
        return 5;
    else 
        return mod;
}

Seems simple, if it's modulus 5 is 0, then just return 5.

Upvotes: 0

Related Questions