小红拿到了一个正整数,她准备随机选择该数的一个数位,并将这个数位随机改成’1’~’9’中任意一个数字(请注意,修改后可能和原数相同)。小红想知道,她修改一次后,这个数变成素数的概率是多少?
区块链毕设网qklbishe.com为您提供问题的解答
小红拿到了一个正整数,她准备随机选择该数的一个数位,并将这个数位随机改成’1’~’9’中任意一个数字(请注意,修改后可能和原数相同)。小红想知道,她修改一次后,这个数变成素数的概率是多少?
优化的空间还很大。
def power(a, b, m): result = 1 a %= m while b > 0: if b % 2 != 0: result = (result * a) % m b >>= 1 a = (a * a) % m return result def is_prime(n): if n < 2: return False if n != 2 and n % 2 == 0: return False s = ((n - 1) & (-(n - 1))).bit_length() - 1 d = (n - 1) >> s witnesses = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37] for a in witnesses: if a >= n: break x = power(a, d, n) if x == 1&nbs***bsp;x == n - 1: continue for _ in range(s - 1): x = power(x, 2, n) if x == n - 1: break else: return False return True def calculate_prime_probability(n): digits = [] while n > 0: digits.append(n % 10) n //= 10 digits.reverse() total_primes = 0 for i, digit in enumerate(digits): for new_digit in range(1, 10): new_number = 0 for j, d in enumerate(digits): new_number *= 10 if i == j: new_number += new_digit else: new_number += d if is_prime(new_number): total_primes += 1 return total_primes / (len(digits) * 9) n = int(input()) probability = calculate_prime_probability(n) print("{:.12f}".format(probability))
use std::io::{self, BufRead, Write}; fn power(mut a: i128, mut b: i128, m: i128) -> i128 { let mut result = 1; a %= m; while b > 0 { if b % 2 != 0 { result = (result * a) % m; } b >>= 1; a = (a * a) % m; } result } fn is_prime(n: i128) -> bool { if n < 2 { return false; } if n != 2 && n % 2 == 0 { return false; } let s = ((n - 1) as u128).trailing_zeros() as i128; let d = (n - 1) / 2i128.pow(s as u32); let witnesses: [i128; 12] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]; 'next_witness: for &a in witnesses.iter().take_while(|&&x| x <= n - 1) { let mut x = power(a, d, n); if x == 1 || x == n - 1 { continue; } for _r in 1..s { x = power(x, 2, n); if x == n - 1 { continue 'next_witness; } } return false; } true } fn calculate_prime_probability(mut n: i128) -> f64 { let mut digits = Vec::new(); while n > 0 { digits.push(n % 10); n /= 10; } digits.reverse(); let mut total_primes = 0; for (i, &digit) in digits.iter().enumerate() { for new_digit in 1..=9 { // if new_digit == digit as i128 { // continue; // Same digit, skip // } let mut new_number = 0i128; for (j, &d) in digits.iter().enumerate() { new_number *= 10; if i == j { new_number += new_digit; } else { new_number += d as i128; } } if is_prime(new_number) { total_primes += 1; } } } total_primes as f64 / (digits.len() * 9) as f64 } fn main() { let n: i128 = io::stdin().lock().lines().next().unwrap().unwrap().trim().parse().unwrap(); let probability = calculate_prime_probability(n); println!("{:.12}", probability); }
编辑于 今天 17:44:51
以上就是关于问题小红拿到了一个正整数,她准备随机选择该数的一个数位,并将这个数位随机改成’1’~’9’中任意一个数字(请注意,修改后可能和原数相同)。小红想知道,她修改一次后,这个数变成素数的概率是多少?的答案
欢迎关注区块链毕设网-
专业区块链毕业设计成品源码,定制。
区块链NFT链游项目方科学家脚本开发培训