Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Returning the value of nth power of iota(i) using JavaScript
In mathematics, the imaginary unit i is defined as the square root of -1. When calculating powers of i, the results follow a cyclic pattern that repeats every 4 powers.
Mathematical Background
The imaginary unit i has the following properties:
i = ?(-1) i² = -1 i³ = -i i? = 1
Since i? = 1, the pattern repeats every 4 powers. This means we can use the modulo operator to determine the result for any power of i.
Power Pattern
| Power (n % 4) | Result (i?) |
|---|---|
| 0 | 1 |
| 1 | i |
| 2 | -1 |
| 3 | -i |
JavaScript Implementation
const num = 657;
const findNthPower = (num = 1) => {
switch(num % 4){
case 0:
return '1';
case 1:
return 'i';
case 2:
return '-1';
case 3:
return '-i';
};
};
console.log(`i^${num} = ${findNthPower(num)}`);
i^657 = i
Testing Multiple Powers
const findNthPower = (num = 1) => {
switch(num % 4){
case 0:
return '1';
case 1:
return 'i';
case 2:
return '-1';
case 3:
return '-i';
};
};
// Test different powers
for(let n = 0; n <= 10; n++) {
console.log(`i^${n} = ${findNthPower(n)}`);
}
i^0 = 1 i^1 = i i^2 = -1 i^3 = -i i^4 = 1 i^5 = i i^6 = -1 i^7 = -i i^8 = 1 i^9 = i i^10 = -1
Alternative Implementation
We can also use an array-based approach for cleaner code:
const findNthPowerArray = (num) => {
const powers = ['1', 'i', '-1', '-i'];
return powers[num % 4];
};
console.log(`i^657 = ${findNthPowerArray(657)}`);
console.log(`i^1000 = ${findNthPowerArray(1000)}`);
i^657 = i i^1000 = 1
Conclusion
Powers of the imaginary unit i follow a predictable cycle of 4. Using the modulo operator with 4, we can efficiently calculate any power of i without complex mathematical operations.
Advertisements
