题目链接
题目描述
九九乘法表是学习乘法时必须要掌握的。在不同进制数下,需要不同的乘法表。
例如, 四进制下的乘法表如下所示:
1*1=1
2*1=2 2*2=10
3*1=3 3*2=12 3*3=21
请注意,乘法表中两个数相乘的顺序必须为样例中所示的顺序,不能随意交换两个乘数。
给定 P P P,请输出 P P P 进制下的乘法表。
输入格式
输入一个整数 P P P。
输出格式
输出 P P P 进制下的乘法表。 P P P 进制中大于等于 10 10 10 的数字用大写字母 A 、 B 、 C 、 ⋯ A、B、C、⋯ A、B、C、⋯ 表示。
输入输出样例
输入
4
输出
1*1=1
2*1=2 2*2=10
3*1=3 3*2=12 3*3=21
输入
8
输出
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=11
4*1=4 4*2=10 4*3=14 4*4=20
5*1=5 5*2=12 5*3=17 5*4=24 5*5=31
6*1=6 6*2=14 6*3=22 6*4=30 6*5=36 6*6=44
7*1=7 7*2=16 7*3=25 7*4=34 7*5=43 7*6=52 7*7=61
解法:模拟
我们可以用 “短除法”,将十进制的数转换成任意 k k k 进制的数。
例如,下面将 19 19 19 转换为 3 3 3 进制的数:
19 / 3 = 6 ... 1
6 / 3 = 2 ... 0
2 / 3 = 0 ... 2
所以最终 19 19 19 的 3 3 3 进制数为 ( 201 ) 3 (201)_3 (201)3。
时间复杂度: O ( n 2 ) O(n^2) O(n2)
C++代码:
#include <iostream>
#include <algorithm>
using namespace std;
int n;
char fun(int x){
if(x < 10)
{
return '0' + x;
}
else
{
return 'A' + (x - 10);
}
}
string ten_to_k(int x)
{
string s;
while(x)
{
s.push_back(fun(x % n));
x /= n;
}
reverse(s.begin(), s.end());
return s;
}
void solve()
{
cin>>n;
for(int i = 1;i < n;i++)
{
for(int j = 1;j <= i;j++)
{
cout<<ten_to_k(i) + "*" + ten_to_k(j) + "=" + ten_to_k(i * j) <<" ";
}
cout<<'\n';
}
}
int main(){
int t = 1;
while(t--)
{
solve();
}
return 0;
}
Java代码:
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static int n;
public static char fun(int x)
{
if(x < 10)
{
return (char)(x + '0');
}
else
{
return (char)('A' + (x - 10));
}
}
public static String tenToK(int x)
{
StringBuilder sb = new StringBuilder();
while(x > 0)
{
sb.append(fun(x % n));
x /= n;
}
sb.reverse();
return sb.toString();
}
public static void main(String[] args) throws Exception{
n = Integer.parseInt(in.readLine().trim());
for(int i = 1;i < n;i++)
{
for(int j = 1;j <= i;j++)
{
System.out.print(tenToK(i) + "*" + tenToK(j) + "=" + tenToK(i * j) + " ");
}
System.out.println();
}
}
}