算法——Locker doors

题目描述

There are n lockers in a hallway numbered sequentially from 1 to n. Initially, all the locker doors are closed. You make n passes by the lockers, each time starting with locker #1. On the ith pass, i = 1, 2, …, n, you toggle the door of every ith locker: if the door is closed, you open it, if it is open, you close it. For example, after the first pass every door is open; on the second pass you only toggle the even-numbered lockers (#2, #4, …) so that after the second pass the even doors are closed and the odd ones are opened; the third time through you close the door of locker #3 (opened from the first pass), open the door of locker #6 (closed from the second pass), and so on. After the last pass, which locker doors are open and which are closed? How many of them are open? Your task is write a program to output How many doors are open after the last pass? Assumptions all doors are closed at first.

输入

a positive numbers n, total doors. n<=100000

输出

a positive numbers ,the total of doors opened after the last pass.

样例输入

10

样例输出

3

代码

#include<iostream>
#include<cmath>
using namespace std;
int main(){
	int n;
	cin>>n;
	int m =sqrt(n);
	cout<<m<<endl;
	return 0;
} 

超级简单有没有?是的,就这样。为什么呢?下面有详细解说。

思路

大多数情况下,每个数的因子是成对出现的,例如数15的因子有1和15,以及3和5,数12的因子有1和12,2和6,3和4,所以有偶数个因子。只有当这个数是完全平方数时,例如1,4,9,16,25,36等等,它的因子除成对出现的以外,还有它的整数平方根作为单独的因子,这些完全平方数的因子数为奇数。
最后一次经过后,只有编号为1,4,9,16,25,36,49,81…的门会开着,其余编号的门都关着。打开的门总数为(sqrt(n))
图描述

发布了7 篇原创文章 · 获赞 44 · 访问量 240

猜你喜欢

转载自blog.csdn.net/qq_45703420/article/details/105091259
今日推荐