'Which C/C++ data type should I use for PHI(N) calculator?
I found a source code online for calculating PHI.
I made some small adjustments to the variable types, such as using an unsigned long int, however I am limited to input numbers that are too small for my experiments. Within the code you can see two printf() functions, the first outputs the correct answer, however the second does not. This is a problem, because I plan to use longer numbers, around 255 digits length.
Additionally, I would like the option to list PHI(N) which are the numbers relatively prime with n, and another option to only list the numbers which are not. I am sure that would be some small changes to the phi() function?
I am aware that with longer inputs my program might never finish the task, this is just an experiment.
Here is the source code.
// C program to calculate Euler's Totient Function
#include <stdio.h>
unsigned long phi(unsigned long n)
{
unsigned long result = n; // Initialize result as n
// Consider all prime factors of n and subtract their
// multiples from result
for (unsigned long p = 2; p * p <= n; ++p) {
// Check if p is a prime factor.
if (n % p == 0) {
// If yes, then update n and result
while (n % p == 0)
n /= p;
result -= result / p;
}
}
// If n has a prime factor greater than sqrt(n)
// (There can be at-most one such prime factor)
if (n > 1)
result -= result / n;
return result;
}
// Driver program to test above function
int main()
{
printf("%lui", phi(1213454642); // <--- Correct Answer :-)
printf("%lui", phi(12134546420740369495582010454127270456626288776132)); // <--- Wrong answer!
return 0;
}
Update I resolved the first problem with the integer limit being too small using InfInt library header file. Now just waiting on the other questions to be resolved.
#include <stdio.h>
#include <assert.h>
// #define USE_PROFINY
#include "/home/username/Desktop/whatever/path/sercantutar-infint-fc767ed/InfInt.h"
InfInt phi(InfInt n)
{
InfInt result = n; // Initialize result as n
// Consider all prime factors of n and subtract their
// multiples from result
for (InfInt p = 2; p * p <= n; ++p) {
// Check if p is a prime factor.
if (n % p == 0) {
// If yes, then update n and result
while (n % p == 0)
n /= p;
result -= result / p;
}
}
// If n has a prime factor greater than sqrt(n)
// (There can be at-most one such prime factor)
if (n > 1)
result -= result / n;
return result;
}
int main()
{
std::cout << phi("1213454642") << std::endl; // <--- Gives correct answer :-)
std::cout << phi("12134546420740369495582010454127270456626288776132") << std::endl; // <--- Waiting on this InfInt to check...
// ^ Trying to get the above to output cout: 5515691438708508277063223066426600430204924080000
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
