切換
舊版
前往
大廳
主題

UVA 10433

NEKROS | 2021-05-19 15:33:13 | 巴幣 0 | 人氣 135

因為測資可能達到2000位數,因此不能用int或double之類的資料型態儲存,需使用字串儲存。因數字極大,想必也不能直接做平方計算。因為我們實際不需要將整個平方的結果算出,只需要後面幾位的值即可,經由觀察直式可發現第n位(最小位數為第一位數)的值,可藉由前n位的數交叉相乘後相加,並加上上一位數的進位值,取10的餘數後得到。因此只要檢查到有與測資不相同的數字即可停止。

因輸入可能會有不定個0在整數前(如0625,001等),因此我們必須有方法可判別這些測資。我的方法為額外建立一個與輸入相同的字串,若前面有0,則將前面所有連續的0去除,若結果為個位數或是0位數則代表無須檢測,可直接輸出非Automorphic Numbers。因為若輸入無多餘的0,且為二位數以上,則平方後的位數必比原先位數還多,便可直接做檢查而不會發生錯誤判斷的情形。

Source Code(C++):
#include<iostream>
#include<string>
//#include<fstream>

using namespace std;

int main(){
string input;
int next = 0;//store the number for next iteration
bool flag;
//ofstream out("result.txt");
while(cin>>input){
if(input == "0" || input == "1"){//follow the condition this problem provided
cout<<"Not an Automorphic number."<<endl;
continue;
}
string input_copy = input;//save a copy of input,since input will be changed later
flag = true;//save whether the whole check is passed
next = 0;
if(input[0] == '0'){ //since input would include '0's before normal numbermwe must check
int count;
for(count = 0;count < input.size();count++){//save how many 0s in the input
if(input[count] != '0')
break;
}
input.erase(input.begin(),input.begin()+count);//erase those 0s
if(input.size() <= 0 || (input.size() == 1 ) ){//if the input becomes 0 digit or only one number(which is definitely not automorphic),then output result
cout<<"Not an Automorphic number."<<endl;
continue;
}
//cout<<input.size()<<endl;
//cout<<input<<' '<<input_copy<<endl;
}
//char *digits = new char[input.size()*2];
for(int count = 0 ;count < input_copy.size();count++){//compute evert digit and compare until a different digit show up
int temp = 0;
for(int add = 0;add <= count;add++){
int t1,t2;//after observering,a digit after square can be calculated
t1 = (int)input_copy[input_copy.size()-1-add]-48;//by product the number on diagonal,the amount is depended on 'count'
t2 = (int)input_copy[input_copy.size()-1-count+add]-48;//ex:625's first(min) digit is ((5*5)%10)=5,second:(5*2+2*5+2)%10=2
//cout<<input.size()-1-add<<endl;//third:(5*6+2*2+6*5+6)%10=6
//cout<<t1<<' '<<t2<<endl;
temp += t1*t2;
//cout<<temp<<' ';
}
//cout<<endl;
temp += next;
next = temp/10;//save for next iteration
temp %= 10;//the value of this iteration's digit
//cout<<next<<' '<<temp<<endl;
if(temp != ((int)input_copy[input_copy.size()-1-count]-48)){//if the digit doesn't match to original one,break
cout<<"Not an Automorphic number."<<endl;
flag = false;
break;
}
}
if(flag){//if all digit conform the original input,output answer
cout<<"Automorphic number of "<<input_copy.size()<<"-digit."<<endl;
}
}
//out.close();
return 0;
}

創作回應

更多創作