init
This commit is contained in:
+45
@@ -0,0 +1,45 @@
|
||||
use std::io::{self, Write};
|
||||
use num_bigint::BigUint;
|
||||
|
||||
fn log_2(x: BigUint) -> u64 {
|
||||
x.bits() - 1
|
||||
}
|
||||
|
||||
fn is_prime(number: BigUint) -> bool {
|
||||
let a = log_2(number.clone()+1u8);
|
||||
if BigUint::from(2u8).pow(a as u32)-BigUint::from(1u8) != number {
|
||||
eprintln!("only supports numbers of type (2^x)-1");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let mut last = BigUint::from(4u8)%number.clone();
|
||||
let two = BigUint::from(2u8);
|
||||
for _i in 2..a {
|
||||
last = (last.clone()*last-two.clone())%number.clone();
|
||||
}
|
||||
if last == BigUint::from(0u8) {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut buffer = String::new();
|
||||
let stdin = io::stdin();
|
||||
print!("please enter the number to check: ");
|
||||
io::stdout().flush().expect("could not flush");
|
||||
stdin.read_line(&mut buffer).expect("could not read from stdin");
|
||||
buffer = buffer.trim().to_owned();
|
||||
|
||||
let number = BigUint::parse_bytes(&buffer.as_bytes(), 10).expect("expected number");
|
||||
|
||||
// number = 2^x - 1
|
||||
// x = log2(number + 1)
|
||||
|
||||
if is_prime(number.clone()) {
|
||||
println!("{number} is a prime");
|
||||
} else {
|
||||
println!("{number} is not a prime");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user