标签:
就像这道题的题目一样,真的是一个简单的题目,题意就是一句话:给一个数N求符合公式N = O * 2P的 O 和 P。
下面我们就一起看一下题吧。
Description
Given a positive integer n and the odd integer o and the nonnegative integer p such that n = o2^p.
Example
For n = 24, o = 3 and p = 3.
Task
Write a program which for each data set:
reads a positive integer n,
computes the odd integer o and the nonnegative integer p such that n = o2^p,
writes the result.
Input
The first line of the input contains exactly one positive integer d equal to the number of data sets, 1 <= d <= 10. The data sets follow.
Each data set consists of exactly one line containing exactly one integer n, 1 <= n <= 10^6.
Output
The output should consists of exactly d lines, one line for each data set.
Line i, 1 <= i <= d, corresponds to the i-th input and should contain two integers o and p separated by a single space such that n = o2^p.
Sample Input
1
24
Sample Output
先给看一下我曾经提交很多次,但都超时的代码
<span style="font-size:24px;"><strong>#include<stdio.h> int main() { int d, n, o, p; while(scanf("%d",&d)==1) { for(int j=1;j<=d;j++) { scanf("%d",&n); o=1; p=1; if(n==1) { printf("0 1\n"); } for(int i=2;j<n;i*=2) { if(n==o*i) { break; } else { o++; p++; } } printf("%d %d\n",o,p); } } return 0; }</strong></span>看过我的代码之后,是不是觉得没问题呀,恩,反正当初我觉得就是对,但是,你可以把我的代码自己运行一下,测试数据随便取个奇数就ok啦,如3 23,哎,当初我测试的时候就没测试奇数,测试的全是偶数,XX还嘲笑我。后来得知超时主要是这几个原因:1.算法太简单2.效率太低,前面提到过,编程很讲究效率的3.程序遇到某种测试数据导致死循环。OK,下面看一下我提交后过了的代码吧。
#include<stdio.h> int main() { int d,n,j; while(~scanf("%d",&d)) { for(int i=0;i<d;i++) { scanf("%d",&n); j=0; while(n%2==0) { j++; n=n/2; } printf("%d %d\n",n,j); } } return 0; }
标签:
原文地址:http://blog.csdn.net/unusualnow/article/details/43796991