Created
June 11, 2013 00:23
-
-
Save svagionitis/5753626 to your computer and use it in GitHub Desktop.
[05/30/13] Challenge #126 [Intermediate] Perfect P'th Powers - http://www.reddit.com/r/dailyprogrammer/comments/1fcpnx/053013_challenge_126_intermediate_perfect_pth/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <math.h> | |
| void usage(char *argv0); | |
| unsigned char isPrime(unsigned long num); | |
| int main(int argc, char *argv[]) | |
| { | |
| unsigned long input = 0, result = 0; | |
| unsigned long base = 0, exponent = 0; | |
| if (argc != 2) | |
| { | |
| usage(argv[0]); | |
| exit(1); | |
| } | |
| input = strtoul(argv[1], NULL, 0); | |
| if (isPrime(input)) | |
| { | |
| printf("1 (%lu^1)\n", input); | |
| return 1; | |
| } | |
| for (base = 1;base<input/2;base++) | |
| { | |
| for(exponent = 1;exponent<input;exponent++) | |
| { | |
| result = (unsigned long)pow((double)base, (double)exponent); | |
| if (result == input) | |
| break; | |
| } | |
| if (result == input) | |
| break; | |
| } | |
| printf("%lu (%lu^%lu)\n", exponent, base, exponent); | |
| } | |
| /** | |
| * Print usage infomation in command line. | |
| * @param argv0 The name of the executable | |
| */ | |
| void usage(char *argv0) | |
| { | |
| printf("Usage: %s [number]\n", argv0); | |
| return; | |
| } | |
| /** | |
| * Check if a number is prime. | |
| * @param num The number to check if prime. | |
| */ | |
| unsigned char isPrime(unsigned long num) | |
| { | |
| unsigned long i = 0; | |
| if (num <= 1) | |
| return 0; | |
| if (num == 2) | |
| return 1; | |
| if (!(num % 2) || !(num % 3) || !(num % 5) || !(num % 7)) | |
| return 0; | |
| for (i = 11;i<num;i++) | |
| if (!(num % i)) | |
| return 0; | |
| return 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment