USACO section 3.2 Factorials(dp)

USACO section 3.4 Closed Fences(计算几何+叉积+二分) Closed Fences A closed fence in the plane is a set of non-crossing, connected line segments with N corners (3 i, yi}, i in (1..N). Every pair of adjacent vertices defines a side of the fence. 阅读详情
Factorials

The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit integer on most computers, and 70! is too large for most floating-point variables. Your task is to find the rightmost non-zero digit of n!. For example, 5! = 1 * 2 * 3 * 4 * 5 = 120, so the rightmost non-zero digit of 5! is 2. Likewise, 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040, so the rightmost non-zero digit of 7! is 4.

PROGRAM NAME: fact4

INPUT FORMAT

A single positive integer N no larger than 4,220.

SAMPLE INPUT (file fact4.in)

7

OUTPUT FORMAT

A single line containing but a single digit: the right most non-zero digit of N! .

SAMPLE OUTPUT (file fact4.out)

4

思路:就是求余,不过要注意2和5的影响,因为没有2和5的影响乘积的个位必不为0,也就是答案,但要是有2和5的话有可能产生多重进位

           如:25*104=2600 进了两位,若直接逐个求余,得到答案将是2,但正确答案是6(随便举个,本题阶乘可能不存在这数据,但可能存在类似的的多重进位)

          因此,我选者将2和5的个数用two,five存下来,而相同的2,5个数会产生进位但不影响余数,除去2,5相同的个数后再乘上前面处理的余数(除去2,5的数)求余就是答案

 

具体代码:

       

/*
ID:nealgav1
LANG:C++
PROG:fact4
*/
#include<fstream>
#include<cstring>
using namespace std;
ifstream cin("fact4.in");
ofstream cout("fact4.out");
const int mm=5200;
const int _two[]={6,2,4,8,6,2,4,8};///乘2的余数
int ans[mm];///除去2,5模10的余数
int main()
{
  int m,mid,two=0,five=0;///记录2,5的总个数
  cin>>m;
  ans[1]=1;mid=2;
  for(int i=2;i<=m;i++)
  {
     mid=i;
     /**除去2,5并记录*/
    while(mid%2==0)
    {
      two++;mid/=2;
    }
    while(mid%5==0)
    {
      five++;mid/=5;
    }
    ans[i]=(ans[i-1]*mid)%10;
  }///乘上2,5取余的答案
   if(two>five)
   {
     two-=five;
     ans[m]=(ans[m]*_two[two%4])%10;
   }
   else if(two<five)
   { 
     ans[m]=(ans[m]*5)%10;
   }
  cout<<ans[m]<<"\n";
}


 

 

 

 

USER: Neal Gavin Gavin [nealgav1]
TASK: fact4
LANG: C++

Compiling...
Compile: OK

Executing...
   Test 1: TEST OK [0.000 secs, 3376 KB]
   Test 2: TEST OK [0.000 secs, 3376 KB]
   Test 3: TEST OK [0.000 secs, 3376 KB]
   Test 4: TEST OK [0.000 secs, 3376 KB]
   Test 5: TEST OK [0.000 secs, 3376 KB]
   Test 6: TEST OK [0.000 secs, 3376 KB]
   Test 7: TEST OK [0.000 secs, 3376 KB]
   Test 8: TEST OK [0.000 secs, 3376 KB]
   Test 9: TEST OK [0.000 secs, 3376 KB]
   Test 10: TEST OK [0.000 secs, 3376 KB]

All tests OK.

YOUR PROGRAM ('fact4') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations.

Here are the test data inputs:

------- test 1 ----
1
------- test 2 ----
2
------- test 3 ----
7
------- test 4 ----
14
------- test 5 ----
143
------- test 6 ----
645
------- test 7 ----
777
------- test 8 ----
888
------- test 9 ----
999
------- test 10 ----
1000
Keep up the good work!
Factorials
Russ Cox

The insight for this problem is that 0's at the end of a number come from it being divisible by 10, or equivalently, by 2 and 5. Furthermore, there are always more 2s than 5s in a factorial.

To get the last digit of the factorial, we can run a loop to calculate it modulo 10, as long as we don't include any 2s or 5s in the product. Of course, we want to exclude the same number of 2s and 5s, so that all we're really doing is ignoring 10s. So after the loop, we need to multiply in any extra 2s that didn't have 5s to cancel them out.

/*
PROG: fact4
ID: rsc001
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

void
main(void)
{
	FILE *fin, *fout;
	int n2, n5, i, j, n, digit;

	fin = fopen("fact4.in", "r");
	fout = fopen("fact4.out", "w");
	assert(fin != NULL && fout != NULL);

	fscanf(fin, "%d", &n);
	digit = 1;
	n2 = n5 = 0;
	for(i=2; i<=n; i++) {
		j = i;
		while(j%2 == 0) {
			n2++;
			j /= 2;
		}
		while(j%5 == 0) {
			n5++;
			j /= 5;
		}
		digit = (digit * j) % 10;
	}

	for(i=0; i<n2-n5; i++)
		digit = (digit * 2) % 10;

	fprintf(fout, "%d\n", digit);
	exit(0);
}

 

用Zotero+B站Kimi,我如何把一篇顶会论文快速做成组会PPT(含完整提示词) 本文介绍如何利用Zotero和Kimi快速将顶会论文转化为组会PPT,提升学术汇报效率。通过Zotero的文献管理插件和Kimi的AI提炼技术,实现从论文阅读到PPT生成的全流程自动化,帮助研究者在90分钟内完成高质量汇报准备。 阅读详情

相关推荐

从零到一:海外短剧成品系统源码搭建流程详解及APP+H5交付服务

在当今全球化的数字娱乐浪潮中,海外短剧市场以其独特的文化魅力和广阔的受众基础,正逐渐成为内容创作者与平台运营者争相布局的新蓝海。我为了紧跟时代的发展我翻看了大量的文章,偶然间看到了一篇文章点进去发现他们是专业做短剧开发的,总结下来在这篇文章里分享给大家。

liangyill_的博客 915

Factorial

Factorial         时间限制:1秒    内存限制:256兆 题目描述      Many years later, Alice grow up and she become a high-school student.One day she learned factorial on math class. The fac

AC0.0的专栏 739

关于Win11安装Ubuntu子系统报错:WslRegisterDistribution failed with error 解决办法

Win11安装Ubuntu子系统报错:WslRegisterDistribution failed with error

qq_51908382的博客 3万+

国防科学技术大学第忘记叫啥杯了

1594: Factorials Time Limit: 1 Sec Memory Limit: 128 MB Submit: 207 Solved: 72 [Submit][Status][Web Board] Description The factorial of an integer N, written N!, is the product of al...

weixin_30292843的博客 118

华为2288H-V5服务器做raid的详细步骤

操作步骤 服务器启动界面 按del键进入设置输入密码,2288H-v5默认密码是Admin@9000 移动光标选择device manager 驱动管理选择configurationutility 配置管理 选择main menu 主菜单 选择第一个 configuration management 配置管理 选择create virtual driver 创建虚拟驱动选择select RAID level 选择RAID等级选择level-5 选择select drivers 选择驱......

weixin_46041124的博客 1万+

matlab SAR图像的多视滤波

单视复数数据(Single Look Comple)是原始的最高分辨率数据,但是从单个像元散射的雷达回波信号的相干叠加,导致强度信息有很多噪声。SAR的多视处理是对SLC数据方位向和/或距离向做平均,得到的结果是多视后的强度数据。多视处理可以提高SAR图像的信噪比,有效抑制斑点噪声,但是会降低方位分辨率。

点云侠的博客 542

Factorials(数学)

Factorials The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit i...

Simone chou... 366

25、压电泵致动器变形计算与测量及转弯腔射流特性的有限元分析

本文围绕压电泵致动器的变形计算与测量以及转弯腔射流特性的有限元分析展开研究。通过建立有限元模型和抛物线拟合方法,对压电泵致动器的位移和变形体积进行了详细计算,并探讨了其对传感器性能的影响。同时,利用ANSYS软件对转弯腔在不同角速率输入下的射流特性进行了仿真分析,揭示了流场分布随角速率变化的规律。研究成果为压电流体角速率传感器的设计优化提供了理论依据和技术支持。

ooo22的博客 134

usaco Chapter 3 section 3.2 Factorials

/*ID: niepeng1LANG: C++TASK:fact4*//*          FactorialsThe factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very

china1000的专栏 654

【人工智能】向量数据库全生命周期数据安全防护体系:破解向量化与检索双环节泄露风险

大模型时代,向量数据库已成为RAG(检索增强生成)架构、语义检索、多模态应用的核心基础设施,解决了大模型幻觉、长上下文窗口限制、私有知识落地等核心痛点。但行业普遍存在认知误区:将Embedding向量等同于“无害的语义压缩乱码”,忽视了向量数据原生的泄露风险。

奶爸的编程之路,也就一周冷个三天 169

STM32F103/F407/H743不同GPIO速度配置(HAL库)对应的最高速度

详细介绍了STM32F103/F407/H743不同GPIO速度配置(HAL库)对应的最高速度。

kevin1499的博客 5603

C++——USACO Section 3.2 题解

Factorials The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bi

McDonnell_Douglas的博客 1023

YOLOv5源码逐行超详细注释与解读(2)——推理部分detect.py

全网最详细的YOLOv5之推理部分detect.py源码逐行注释,近四万字的超详细讲解!小白入门必看!

路人贾的博客 5万+

usaco-Section 3.2-Factorials

Factorials The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit in...

weixin_30378623的博客 150

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain&#39;s apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath(&#39;DeepLearnToolbox&#39;));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand(&#39;state&#39;,0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = &#39;sigm&#39;;%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, &#39;Too big error&#39;);```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, &#39;Too big error&#39;);```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

USACO:Factorials

转载自So You Try的博客 Factorials The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large

youzn99的博客 384

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

USACO section 3.1 Contact(AC自动机)

Contact IOI'98 The cows have developed a new interest in scanning the universe outside their farm with radiotelescopes. Recently, they noticed a very curious microwave pulsing emission sent right f

nealgavin的专栏 9384

USCAO section 1.3 Calf Flac

Calf Flac It is said that if you give an infinite number of cows an infinite number of heavy-duty laptops (with very large keys), that they will ultimately produce all the world's great palindromes

nealgavin的专栏 6656

USACO section 1.5 Checker Challenge(dfs深搜)

Checker ChallengeExamine the 6x6 checkerboard below and note that the six checkers are arranged on the board so that one and only one is placed in each row and each column, and there is never more tha

nealgavin的专栏 1924

USACO section 2.3 Longest Prefix(dp)

Longest Prefix IOI'96 The structure of some biological objects is represented by the sequence of their constituents, where each part is denote by an uppercase letter. Biologists are interested in

nealgavin的专栏 1487

USACO section 2.4 Cow Tours(并查集+最短路)

Cow Tours Farmer John has a number of pastures on his farm. Cow paths connect some pastures with certain other pastures, forming a field. But, at the present time, you can find at least two pasture

nealgavin的专栏 1406

USACO section3.1 Shaping Regions(漂浮法)

Shaping Regions N opaque rectangles (1 <= N <= 1000) of various colors are placed on a white sheet of paper whose size is A wide by B long. The rectangles are put with their sides parallel to the s

nealgavin的专栏 1052

USACO section 2.2 Runaround Numbers

Runaround Numbers Runaround numbers are integers with unique digits, none of which is zero (e.g., 81362) that also have an interesting property, exemplified by this demonstration: If you start

nealgavin的专栏 991

USACO section 3.1 Stamps(dp)

Stamps Given a set of N stamp values (e.g., {1 cent, 3 cents}) and an upper limit K to the number of stamps that can fit on an envelope, calculate the largest unbroken list of postages from 1 cent

nealgavin的专栏 980

USCAO section 4.1 Fence Loops(最短路,最小环,5级)

Fence Loops The fences that surround Farmer Brown's collection of pastures have gotten out of control. They are made up of straight segments from 1 through 200 feet long that join together only a

nealgavin的专栏 941

USACO section 1.5 Superprime Rib(深搜)

Superprime RibButchering Farmer John's cows always yields the best prime rib. You can tell prime ribs by looking at the digits lovingly stamped across them, one by one, by FJ and the USDA. Farmer John

nealgavin的专栏 938

USACO section 2.2 Party Lamps

Party Lamps IOI 98 To brighten up the gala dinner of the IOI'98 we have a set of N (10 <= N <= 100) colored lamps numbered from 1 to N. The lamps are connected to four buttons: Button 1: Wh

nealgavin的专栏 914
上一篇: USACO section 3.1 Contact(AC自动机)
下一篇: USACO section 3.2 Stringsobits(组合数学)
剑不飞
博客等级 码龄15年 86粉丝 505原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址