机试训练营--基础--数学

图片说明
1.素数判定
对于表达式n^2+n+41,当n在(x,y)范围内取整数值时(包括x,y)(-39<=x<y<=50),判定该表达式的值是否都为素数。
Input
输入数据有多组,每组占一行,由两个整数x,y组成,当x=0,y=0时,表示输入结束,该行不做处理。
Output
对于每个给定范围内的取值,如果表达式的值都为素数,则输出"OK",否则请输出“Sorry”,每组输出占一行。
Sample Input
0 1
0 0
Sample Output
OK
我写的:

标准:

#include<iostream>
#include<cstdio>
using namespace std;
bool isPrime(int x) {
    if(x<2) return false;
    for (int i = 2; i * i < x; i++) {
        if (x % i == 0) return false;
    }
    return true;
}
bool isAllPrime(int l, int r) {
    for (int i = l; i <= r; i++) {
        if (!isPrime(i * i + i + 41)) return false;
    }
    return true;
}
int main() {
    int x, y;
    while (scanf("%d%d", &x, &y) != EOF) {
        if (x == 0 && y == 0)break;
        if (isAllPrime(x, y))printf("OK\n");
        else printf("Sorry\n");
    }
    return 0;
}

2.最小公倍数
给定两个正整数,计算这两个数的最小公倍数。

Input
输入包含多组测试数据,每组只有一行,包括两个不大于1000的正整数.

Output
对于每个测试用例,给出这两个数的最小公倍数,每个实例输出一行。

Sample Input
10 14

Sample Output
70

#include<cstdio>
#include<iostream>
using namespace std;
int gcd(int x, int y) {
    int t;
    while (y != 0) {
        t = x % y;
        x = y;
        y = t;
    }
    return x;
}
int main() {
    int x, y;
    while (scanf("%d%d", &x, &y) != EOF) {
        printf("%d\n", x * y / gcd(x, y));
    }
    return 0;
}

3.人见人爱A^B
Problem Description
求A^B的最后三位数表示的整数。
说明:A^B的含义是“A的B次方”

Input
输入数据包含多个测试实例,每个实例占一行,由两个正整数A和B组成(1<=A,B<=10000),如果A=0, B=0,则表示输入数据的结束,不做处理。

Output
对于每个测试实例,请输出A^B的最后三位表示的整数,每个输出占一行。

Sample Input
2 3
12 6
6789 10000
0 0

Sample Output
8
984
1

#include<iostream>
#include<cstdio>
using namespace std;
typedef long long LL;
//快速幂的标准模板
LL quickmod(int a, int b, int mod) {
    LL res = 1;
    while (b) {
        if (b & 1) res = (res * a) % mod;
        a = a * a % mod;
        b = b >> 1;
    }
    return res;
}
int main() {
    int a, b;
    while (scanf("%d%d", &a, &b) != EOF) {
        if (a == 0 && b == 0)break;
        printf("%lld\n", quickmod(a, b, 1000));
    }

    return 0;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务