什么是获得(-1)^ n中的正确方法是什么? [英] What is the correct way to obtain (-1)^n?

查看:159
本文介绍了什么是获得(-1)^ n中的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多算法需要计算( - 1)^ N (均为整数),通常是在一系列的因素。也就是说,一个因素是 1 奇数n和 1 为偶数n。在C或C ++环境下,人们经常看到:

 #包括<的iostream>
#包括< CMATH>
诠释的main(){
   INT N = 13;
   性病::法院<<性病::战俘(-1,N)其中;<的std :: ENDL;
}
 

什么是好还是通常的惯例?(或别的东西),

 的std :: POW(-1,N)
性病::战俘(-1,N%2)
(正%2 -1:1)
(1-2 *(N%2))//(提供不正确的值负N)
 

编辑: 此外,用户@SeverinPappadeux提出了基于阵列的查找另一种选择(一个全球性的?)。我对它的版本是:

  const int的资源[] {1,1,-1};都需要负模的结果//三种元素
const int的* const的m1pow = RES + 1;
...
m1pow [N%2]
 

解决方案

您可以使用(N&安培; 1),而不是 N%2 << 1 而不是 * 2 ,如果你想成为超级迂腐,呃我的意思是优化的。
因此,在一个8086处理器,计算速度最快的方式是:

1 - ((N&安培; 1) - =;< 1)

我只是想在这里澄清这个答案的来源。楼主alfC确实张贴了很多不同的方法来计算一个出色的工作(-1)的n次方有些是比别人快。
时下的处理器是一样快,他们正在和优化编译器为好,因为他们是我们的一般的值的可读性比从操作剃了几个CPU周期的轻微(甚至可以忽略不计)的改进。
曾经有一段时间,当一个合格的编译器统治地球和MUL操作是新的,颓废;在那些日子里的2的操作电源是用于无偿优化的邀请。

Many algorithms require to compute (-1)^n (both integer), usually as a factor in a series. That is, a factor that is -1 for odd n and 1 for even n. In a C or C++ environment, one often sees:

#include<iostream>
#include<cmath>
int main(){
   int n = 13;
   std::cout << std::pow(-1, n) << std::endl;
}

What is better or the usual convention? (or something else),

std::pow(-1, n)
std::pow(-1, n%2)
(n%2?-1:1)
(1-2*(n%2))  // (gives incorrect value for negative n)

EDIT: In addition, user @SeverinPappadeux proposed another alternative based on (a global?) array lookups. My version of it is:

const int res[] {-1, 1, -1}; // three elements are needed for negative modulo results
const int* const m1pow = res + 1; 
...
m1pow[n%2]

解决方案

You can use (n & 1) instead of n % 2 and << 1 instead of * 2 if you want to be super-pedantic, er I mean optimized.
So the fastest way to compute in an 8086 processor is:

1 - ((n & 1) << 1)

I just want to clarify where this answer is coming from. The original poster alfC did an excellent job of posting a lot of different ways to compute (-1)^n some being faster than others.
Nowadays with processors being as fast as they are and optimizing compilers being as good as they are we usually value readability over the slight (even negligible) improvements from shaving a few CPU cycles from an operation.
There was a time when one pass compilers ruled the earth and MUL operations were new and decadent; in those days a power of 2 operation was an invitation for gratuitous optimization.

这篇关于什么是获得(-1)^ n中的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆