做窗帘网站图片,购物网站排行榜前十名,营销型网站模板免费下载,太原 招聘 网站建设 技术经理【NOIP普及组】质因数分解 C语言代码C代码Java代码Python代码 #x1f490;The Begin#x1f490;点点关注#xff0c;收藏不迷路#x1f490; 已知正整数 n 是两个不同的质数的乘积#xff0c;试求出较大的那个质数。
输入
输入只有一行#xff0c;包含一个正整数… 【NOIP普及组】质因数分解 C语言代码C代码Java代码Python代码 The Begin点点关注收藏不迷路
已知正整数 n 是两个不同的质数的乘积试求出较大的那个质数。
输入
输入只有一行包含一个正整数 n。
输出
输出只有一行包含一个正整数 p即较大的那个质数。
样例输入
21样例输出
7提示
【数据范围】 对于 60%的数据 6≤n≤1000。 对于 100%的数据 6≤n≤2∗10^9 。
C语言代码
#include stdio.h
#include math.hint main() {int n; // 存储输入的正整数scanf(%d, n); // 读取输入的正整数int maxPrime 0; // 用于存储较大的质数初始化为0// 从2开始遍历到n的平方根因为一个数的因数不会超过它的平方根for (int i 2; i sqrt(n); i) { if (n % i 0) { // 如果i是n的因数int otherFactor n / i; // 计算另一个因数// 判断i和另一个因数是否都是质数int isIprime 1;for (int j 2; j sqrt(i); j) {if (i % j 0) {isIprime 0;break;}}int isOtherFactorPrime 1;for (int j 2; j sqrt(otherFactor); j) {if (otherFactor % j 0) {isOtherFactorPrime 0;break;}}// 如果i和另一个因数都是质数更新较大的质数if (isIprime isOtherFactorPrime) {maxPrime (i otherFactor)? i : otherFactor;}}}printf(%d\n, maxPrime); // 输出较大的质数return 0;
}C代码
#include iostream
#include cmathint main() {int n; // 存储输入的正整数std::cin n; // 读取输入的正整数int maxPrime 0; // 用于存储较大的质数初始化为0// 从2开始遍历到n的平方根因为一个数的因数不会超过它的平方根for (int i 2; i std::sqrt(n); i) { if (n % i 0) { // 如果i是n的因数int otherFactor n / i; // 计算另一个因数// 判断i和另一个因数是否都是质数bool isIprime true;for (int j 2; j std::sqrt(i); j) {if (i % j 0) {isIprime false;break;}}bool isOtherFactorPrime true;for (int j 2; j std::sqrt(otherFactor); j) {if (otherFactor % j 0) {isOtherFactorPrime false;break;}}// 如果i和另一个因数都是质数更新较大的质数if (isIprime isOtherFactorPrime) {maxPrime (i otherFactor)? i : otherFactor;}}}std::cout maxPrime std::endl; // 输出较大的质数return 0;
}Java代码
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner scanner new Scanner(System.in);int n scanner.nextInt(); // 读取输入的正整数int maxPrime 0; // 用于存储较大的质数初始化为0// 从2开始遍历到n的平方根因为一个数的因数不会超过它的平方根for (int i 2; i Math.sqrt(n); i) { if (n % i 0) { // 如果i是n的因数int otherFactor n / i; // 计算另一个因数// 判断i和另一个因数是否都是质数boolean isIprime true;for (int j 2; j Math.sqrt(i); j) {if (i % j 0) {isIprime false;break;}}boolean isOtherFactorPrime true;for (int j 2; j Math.sqrt(otherFactor); j) {if (otherFactor % j 0) {isOtherFactorPrime false;break;}}// 如果i和另一个因数都是质数更新较大的质数if (isIprime isOtherFactorPrime) {maxPrime (i otherFactor)? i : otherFactor;}}}System.out.println(maxPrime); // 输出较大的质数scanner.close();}
}Python代码
import mathn int(input()) # 读取输入的正整数maxPrime 0 # 用于存储较大的质数初始化为0# 从2开始遍历到n的平方根因为一个数的因数不会超过它的平方根
for i in range(2, int(math.sqrt(n)) 1): if n % i 0: # 如果i是n的因数otherFactor n // i # 计算另一个因数# 判断i和另一个因数是否都是质数isIprime all(i % j! 0 for j in range(2, int(math.sqrt(i)) 1))isOtherFactorPrime all(otherFactor % j! 0 for j in range(2, int(math.sqrt(otherFactor)) 1))# 如果i和另一个因数都是质数更新较大的质数if isIprime and isOtherFactorPrime:maxPrime max(i, otherFactor)print(maxPrime) # 输出较大的质数The End点点关注收藏不迷路