c++给定整数x和整数y,输出x的y次方。题目保证不存在x=0 y=0的情况。 输入格式: 第一行两个整数:x,y(0 <= x,y <= 9)。 输出格式: 输出x的y次方。
时间: 2023-11-29 17:05:20 浏览: 60
C++ 代码
#include <iostream>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
int res = 1;
for (int i = 0; i < y; i++)
{
res *= x;
}
cout << res << endl;
return 0;
}
相关问题
给定整数x和整数y,输出x的y次方。题目保证不存在x=0 y=0的情况。 输入格式: 第一行两个整数:x,y(0 <= x,y <= 9)。 输出格式: 输出x的y次方。 输入样例: 3 5 输出样例: 243
思路:直接使用循环求幂即可。
时间复杂度:$O(y)$。
C++ 代码
```
#include <iostream>
using namespace std;
int main()
{
int x, y;
cin >> x >> y;
int res = 1;
for (int i = 0; i < y; i ++ )
res *= x;
cout << res << endl;
return 0;
}
```
Java 代码
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x = sc.nextInt(), y = sc.nextInt();
int res = 1;
for (int i = 0; i < y; i ++ )
res *= x;
System.out.println(res);
}
}
```
Python 代码
```python
x, y = map(int, input().split())
res = 1
for i in range(y):
res *= x
print(res)
```
用c++写一个 给定整数x和n求x的幂函数 mod 1003
好的,我可以帮您解答这个问题。
以下是使用 C 语言编写求 x 的 n 次方函数 mod 1003 的代码:
```c
#include <stdio.h>
int pow_mod(int x, int n, int mod) {
int res = 1;
while(n > 0) {
if(n % 2 == 1) {
res = (res * x) % mod;
}
x = (x * x) % mod;
n /= 2;
}
return res;
}
int main() {
int x = 2;
int n = 10;
int mod = 1003;
int result = pow_mod(x, n, mod);
printf("%d\n", result);
return 0;
}
```
上述代码中,pow_mod 函数通过快速幂算法求解 x 的 n 次方,将结果对 mod 取模后返回。在 main 函数中,我们设定 x=2,n=10,mod=1003,然后调用 pow_mod 函数得到最终结果并输出。你可以根据需要修改 x、n、mod 的值,或者修改 main 函数调用方式来获取不同的计算结果。