กำหนดจำนวนเต็มเป็นอินพุต เป้าหมายคือการหาจำนวนศูนย์ต่อท้ายในผลิตภัณฑ์ 11 X 22 X 33 X…X num num .
ตัวอย่าง
อินพุต
num=5
ผลลัพธ์
Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5
คำอธิบาย
The number of 2s and 5s in the product will be: 11 * 22* 33* 44* 55=11 * 22* 33* (22)4* 55. So total 10 2s and 5 5s, minimum is 5 so trailing zeroes will be 5.
อินพุต
num=10
ผลลัพธ์
Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5
คำอธิบาย
The number of 2s and 5s in the product will be: 11 *22*33*44*55*66 *77*88*99*1010 = 11 *22*33*44*55*66 *77*88*99*(2*5)10. So total 20 2s and 15 5s, minimum is 15 so trailing zeroes will be 15.
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในวิธีนี้ เราจะนับจำนวน 2s และ 5s ในการแยกตัวประกอบเฉพาะของแต่ละตัวเลขในผลิตภัณฑ์ เนื่องจากแต่ละจำนวนถูกยกกำลังของตัวเอง การนับขั้นต่ำของ 2s หรือ 5s ในการแยกตัวประกอบจะทำให้การนับเลขศูนย์ต่อท้าย เนื่องจากแต่ละ 2*5 บวก 0 หนึ่งรายการในผลิตภัณฑ์
-
ใช้จำนวนเต็มเป็นอินพุต
-
ฟังก์ชัน count_trailing(int num) รับค่า num และคืนค่าจำนวนเลขศูนย์ต่อท้ายใน (1^1)*(2^2)*(3^3)*(4^4)*.....
-
นับเริ่มต้นเป็น 0
-
ใช้ตัวแปร temp_2 =0, temp_5 =0 สำหรับการนับ 2s และ 5s
-
ข้ามโดยใช้ลูปจาก i=1 ถึง i<=num.
-
ใช้อุณหภูมิเหมือนฉัน
-
ในขณะที่ temp หารด้วย 2 ลงตัวแล้วให้ลดครึ่งและเพิ่ม i เพื่อนับ temp_2 เป็นจำนวน 2 วินาที
-
ในขณะที่ temp หารด้วย 5 ลงตัวแล้วหารด้วย 5 แล้วบวก i เพื่อนับ temp_5 เป็นจำนวน 5 วินาที
-
นับอย่างน้อยสองครั้งโดยใช้ count =min(temp_2, temp_5)
-
ผลตอบแทนนับเป็นผลลัพธ์
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int count_trailing(int num){
int count = 0;
int temp_2 = 0;
int temp_5 = 0;
for (int i = 1; i <= num; i++){
int temp = i;
while(temp % 2 == 0 && temp > 0){
temp = temp / 2;
temp_2 = temp_2 + i;
}
while (temp % 5 == 0 && temp > 0){
temp = temp / 5;
temp_5 = temp_5+ i;
}
}
count = min(temp_2, temp_5);
return count;
}
int main(){
int num = 5;
cout<<"Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: "<<count_trailing(num);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count of number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. are: 5