本文概述
- C ++
- Java
- Python3
- C#
- PHP
例子 :
Input:num = "12316767678678", a = 10
Output: num (mod a) ≡ 8
这个想法是一一处理所有数字并使用xy(mod a)≡((x(mod a)* y)(mod a))的属性。下面是实现。
感谢utkarsh111建议以下解决方案。
C ++
// C++ program to compute mod of a big number represented
// as string
#include<
iostream>
using namespace std;
// Function to compute num (mod a)
int mod(string num, int a)
{
// Initialize result
int res = 0;
// One by one process all digits of 'num'
for ( int i = 0;
i <
num.length();
i++)
res = (res*10 + ( int )num[i] - '0' ) %a;
return res;
}// Driver program
int main()
{
string num = "12316767678678" ;
cout <
<
mod(num, 10);
return 0;
}
Java
// Java program to compute mod of a big
// number represented as string
import java.io.*;
class GFG {// Function to compute num (mod a)
static int mod(String num, int a)
{// Initialize result
int res = 0 ;
// One by one process all digits of 'num'
for ( int i = 0 ;
i <
num.length();
i++)
res = (res * 10 + ( int )num.charAt(i)
- '0' ) % a;
return res;
}// Driver program
public static void main(String[] args)
{String num = "12316767678678" ;
System.out.println(mod(num, 10 ));
}
}// This code is contributed by vt_m.
Python3
# program to compute mod of a big number
# represented as string# Function to compute num (mod a)
def mod(num, a):# Initialize result
res = 0# One by one process all digits
# of 'num'
for i in range ( 0 , len (num)):
res = (res * 10 + int (num[i])) % a;
return res# Driver program
num = "12316767678678" ;
print (mod(num, 10 ))# This code is contributed by Sam007
C#
// C# program to compute mod of a big
// number represented as string
using System;
public class GFG
{// Function to compute num (mod a)
static int mod(String num, int a)
{// Initialize result
int res = 0;
// One by one process all
// digits of 'num'
for ( int i = 0;
i <
num.Length;
i++)
res = (res * 10 + ( int )num[i]-
'0' ) % a;
return res;
}// Driver code
public static void Main()
{
String num = "12316767678678" ;
Console.WriteLine(mod(num, 10));
}
}// This code is contributed by Sam007
的PHP
<
?php
// PHP program to compute mod
// of a big number represented
// as string// Function to compute num (mod a)
function mod( $num , $a )
{
// Initialize result
$res = 0;
// One by one process
// all digits of 'num'
for ( $i = 0;
$i <
$r = strlen ( $num );
$i ++)
$res = ( $res * 10 +
$num [ $i ] - '0' ) % $a ;
return $res ;
}// Driver Code
$num = "12316767678678" ;
echo mod( $num , 10);
// This code is contributed by ajit
?>
【算法题(如何计算大数的mod())】输出:
8
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。
推荐阅读
- 如何将Mongodb数据库与Node.js连接起来()
- 如何在Golang中比较两个字节切片()
- 如何使用单个Dockerfile合并多个基本镜像()
- Pandas如何组合Groupby和多个聚合函数()
- 如何在C#中检查线程是否处于活动状态()
- Git的安装初次配置以连接github,在第三方软件中配置使用git 命令,提交项目到github的远程仓库出现bug的解决
- win10插入耳机后有电流声怎么办电脑出现回声怎么办
- 网络传输时既有管道流(PipedInputStream 与 PipedOutStream)又有序列化对象反序列化对象(ObjectOutputStream与 ObjectInputStream)
- 安装选择msi格式还是zip(windows下Nodejs zip版下载安装及环境变量配置)