java program to find m%n without using % operator, i got only using %, can some one help me without % operator?

public class mod{
public static void main(String[] args){
int m=3, n=2; 
System.out.print("m%n is"+m%n); 
}}

I want to find m%n without % operator

有帮助吗?

解决方案 4

Try this:

System.out.print("m%n is"+(m-m/n*n));

其他提示

You don't need double. You can just do

int mod = m - m / n * n;

Remainder is calculated as a result of a division and many cpus have an integer divide and remainder in a single operations. For this reason, it is a good idea to put them together so the JIT can optimise them. e.g. the following code could be a single machine code instruction

int a = m / n;
int b = m % n;

This combination is very common for turning integers into text as / 10 and % 10 are used in combination.

It's as easy as

m - n * (m / n);

n * ((double)m / n - m / n) is one way.

This works since m / n will be performed in integer arithmetic, but (double)m / n in floating point due to the promotion of one of the integers.

There are hundreds of ways to do this, as well as the division/multiplication approach you can also do things like this for example:

while (m>=n)
    m-=n;

It gets harder if all loops are banned not just for loops but there are still options such as recursion etc.

Also you can:

m - (m / n) * n;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top