java FindrootInZnZ
x^2+1=0在Z/2Z中有1個根:[1]
x^2+x+1=0在Z/2Z中有0個根:[]
x^2+1=0在Z/5Z中有2個根:[2,3]
x^2+x+1=0在Z/5Z中有0個根:[]
import java.io.*;
import java.util.*;
import java.util.function.Function;
public class FindrootInZnZ{
static int Mod(int ret,int n){
if(ret<0){
int ret1=ret+(-ret+1)*n;
return ret1%n;
}
return ret%n;
}
static Vector Findroot(Function<Integer,Integer> fun,int n){
Vector ret = new Vector();
for(int i=0;i<n;i++){
int newValue=fun.apply(i);
if(Mod(newValue,n)==0){
ret.add(i);
}
}
return ret;
}
static String V2S(Vector v){
String Str = "[";
for (int i = 0; i < v.size(); i++) {
Str+=String.format("%d",v.get(i));
if(i<v.size()-1){
Str+=",";
}
}
Str += "]";
return Str;
}
public static void main(String[] args) {
{
Vector v1 = Findroot(x->x*x+1,2);
String str=V2S(v1);
System.out.printf("x^2+1=0在Z/2Z中有%d個根:%s\n",v1.size(),str);
}
{
Vector v1 = Findroot(x->x*x+x+1,2);
String str=V2S(v1);
System.out.printf("x^2+x+1=0在Z/2Z中有%d個根:%s\n",v1.size(),str);
}
{
Vector v1 = Findroot(x->x*x+1,5);
String str=V2S(v1);
System.out.printf("x^2+1=0在Z/5Z中有%d個根:%s\n",v1.size(),str);
}
{
Vector v1 = Findroot(x->x*x+x+1,5);
String str=V2S(v1);
System.out.printf("x^2+x+1=0在Z/5Z中有%d個根:%s\n",v1.size(),str);
}
}
}