原文:
给定一个正整数 n,在值 1/n 的点之后打印前 k 个数字。您的程序应该避免溢出和浮点运算。 例:
input: n = 3, k = 3
output: 333
input: n = 50, k = 4
output: 0200
强烈建议尽量减少浏览器,先自己试试这个。 我们来考虑一个例子 n = 7,k = 3。1/7 的第一位是‘1’,可以通过做 10/7 的整数值得到。10/7 的余数是 3。下一位是 4,取整数值 30/7 即可。30/7 的余数是 2。接下来的数字是 2,取整数值 20/7 即可
c
#include
using namespace std;
// function to print first k digits after dot in value
// of 1/n. n is assumed to be a positive integer.
void print(int n, int k)
{
int rem = 1; // initialize remainder
// run a loop k times to print k digits
for (int i = 0; i < k; i )
{
// the next digit can always be obtained as
// doing (10*rem)/10
cout << (10 * rem) / n;
// update remainder
rem = (10*rem) % n;
}
}
// driver program to test above function
int main()
{
int n = 7, k = 3;
print(n, k);
cout << endl;
n = 21, k = 4;
print(n, k);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java code to print first k
// digits of 1/n where n is a
// positive integer
import java.io.*;
class gfg
{
// function to print first
// k digits after dot in value
// of 1/n. n is assumed to be
// a positive integer.
static void print(int n, int k)
{
// initialize remainder
int rem = 1;
// run a loop k times to print k digits
for (int i = 0; i < k; i )
{
// the next digit can always be
// obtained as doing (10*rem)/10
system.out.print( (10 * rem) / n);
// update remainder
rem = (10 * rem) % n;
}
}
// driver program
public static void main(string []args)
{
int n = 7, k = 3;
print(n, k);
system.out.println();
n = 21;
k = 4;
print(n, k);
}
}
// this article is contributed by vt_m
python 3
# python code to print first k
# digits of 1/n where n is a
# positive integer
import math
# function to print first k digits
# after dot in value of 1/n. n is
# assumed to be a positive integer.
def print(n, k):
rem = 1 # initialize remainder
# run a loop k times to print
# k digits
for i in range(0, k):
# the next digit can always
# be obtained as doing
# (10*rem)/10
print(math.floor(((10 * rem)
/ n)), end="")
# update remainder
rem = (10*rem) % n
# driver program to test
# above function
n = 7
k = 3
print(n, k);
print(" ")
n = 21
k = 4
print(n, k);
# this code is contributed by sam007.
c
// c# code to print first k digits of
// 1/n where n is a positive integer
using system;
class gfg {
// function to print first
// k digits after dot in value
// of 1/n. n is assumed to be
// a positive integer.
static void print(int n, int k)
{
// initialize remainder
int rem = 1;
// run a loop k times to
// print k digits
for (int i = 0; i < k; i )
{
// the next digit can always be
// obtained as doing (10*rem)/10
console.write( (10 * rem) / n);
// update remainder
rem = (10 * rem) % n;
}
}
// driver program
public static void main()
{
int n = 7, k = 3;
print(n, k);
console.writeline();
n = 21;
k = 4;
print(n, k);
}
}
// this code is contributed by sam007.
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
输出:
142
0476
时间复杂度:0(k)
辅助空间:0(1)
参考: 本文由沙钦供稿。如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处