简体   繁体   English

优化C语言中的数学运算

[英]Optimize mathematical operations in c

I am registered in a web programming c where several algorithmic exercises. 我注册了Web编程c,其中进行了几种算法练习。 I made a very simple problem is as follows: I receive 4 numbers that determine coordinates of 2 corner of a rectangle and have to calculate the area. 我做了一个非常简单的问题,如下所示:我收到4个数字,这些数字确定矩形2个角的坐标,并且必须计算面积。 There is a set of tests and when the second corner is below or to the left of the first (x1> x2 || y1> y2) the program exits. 有一组测试,当第二个角在第一个角的下方或左侧时(x1> x2 || y1> y2),程序退出。 在此处输入图片说明

Exemple: 范例:

Input: 输入:

1 1 4 3
0 0 1 1
9 7 3 6 //Exit

Output: 输出:

6
1

This is my code. 这是我的代码。

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

int main()
{
    while(1) {
        int x1, x2, y1, y2;
        scanf("%d %d %d %d", &x1, &y1, &x2, &y2);//x1 y1 == A, x2 y2 == B
        if(x1 > x2 || y1 > y2)
            return 0;
        printf("%d\n", (x2 - x1) * (y2 - y1));
    }
}

My question is simply a curiosity. 我的问题只是出于好奇。 I solved the problem with a time of "0052", and there are 3 people in front of me that have managed to solve in "0048" and "0024"!. 我用时间“ 0052”解决了这个问题,我前面有3个人成功解决了“ 0048”和“ 0024”! What optimicazion methods can I use to get lower time? 我可以使用哪些优化方法来缩短时间? Probably pointers? 可能是指针?

Some thoughts: 一些想法:

  1. You could use gcc's __builtin_expect() functions to make sure that the conditional is assumed to be false. 您可以使用gcc的__builtin_expect()函数来确保该条件为假。

  2. It's very unlikely that pointers would help you improve your solution. 指针不可能帮助您改进解决方案。

  3. scanf() is probably the really slow part. scanf()可能是最慢的部分。 Rewriting this with a parser that only expected decimal integers would probably be much faster. 用解析器重写该解析器,即只有预期的十进制整数可能会快得多。 Currently, scanf() needs to parse the format string, and the input number could be octal, hexadecimal, or decimal. 当前, scanf()需要解析格式字符串,并且输入数字可以是八进制,十六进制或十进制。 Or could be invalid input. 或可能是无效的输入。 etc. 等等

Not much, but maybe try declaring int x1, x2, y1, y2; 数量不多,但是可以尝试声明int x1, x2, y1, y2; before entering the loop. 进入循环之前。

Here are my suggestions: 这是我的建议:

  1. in the compile statement use: 在compile语句中使用:

     gcc -O3 
  2. place all working variables in global space rather than stack space 将所有工作变量放在全局空间而不是堆栈空间中

     int x1, x2, y1, y2;, area char buffer[100]; int main() { do { fgets( buffer, sizeof(buffer), stdin ); sprintf( buffer, "%d %d %d %d", &x1, &y1, &x2, &y2); x2-=x1; y2-=y1; area = y2*x2; printf("%d\\n",area); // or perhaps puts( itoa(area) ); } while(( 0 <= x2) && (0 <= y2) return(0); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM