創作內容

5 GP

Product of digits (using C++)

作者:Breguet│2014-07-22 10:46:34│巴幣:10│人氣:1333
Product of Digits



題意:
For a given non-negative integer number N , find the minimal natural Q such that the product of all digits of Q is equal N .

輸入一個正整數N,決定有幾個case,再輸入N個數字,找出一個所有digit相乘會等於輸入數的數字(由小到大),若找不到,則印出-1。

輸入範例:
3
1
10
123456789

輸出範例:
1
25
-1

解法:

設定一個方法,裡面有一個大小為1000儲存答案的陣列,先檢查是否為1,的話直接印出一;不是的話再做下列步驟,用for迴圈將這個數字從9檢查到2,看共有幾個2到9的因數,在while裡檢查的則是是否有重複數字的因數,(如81為9*9),有的話就存入陣列。在for迴圈執行結束後,判斷原先輸入的數字是否被除成1,是的話代表有答案,將儲存答案的陣列由後往前全部印出來,若不是1則代表沒有答案,印出-1。

程式:

#include <iostream>

using namespace std;

int main(){
int num;
int does;
void seq_dig(int);
cin >> does ;
for(int i=0;i<does;i++){
cin >> num;
seq_dig(num);
}
return 0;
}

void seq_dig(int num){
int ans[1000];
int store=0;
if(num!=1){

for(int tst_dig=9;tst_dig>1;tst_dig--){
while(num!=1){
if(num%tst_dig){
break; //the tst_dig is not divisor of num

}

else{

num/=tst_dig;

ans[store]=tst_dig;

store++;

}

}

}

if(num==1){

for(int i=store-1;i>=0;i--)

cout <<ans[i] ;

cout <<endl;

}

else{

}

}

else{

cout << "1"<<endl;

}
}

cout << "-1" <<endl;
引用網址:https://home.gamer.com.tw/TrackBack.php?sn=2521885
All rights reserved. 版權所有,保留一切權利

相關創作

留言共 1 篇留言

薯條控
<(_ _)>

03-16 22:28

我要留言提醒:您尚未登入,請先登入再留言

5喜歡★NTUCSIE 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:Binary Searc...

追蹤私訊切換新版閱覽

作品資料夾

ilove487奇幻小說連載中
《克蘇魯的黎明》0667.掉到海裡要先救誰?看更多我要大聲說昨天13:38


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】