Advertisement
Heretiiik

factoriasation

Nov 11th, 2015
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. /*
  8.  * File:   main.c
  9.  * Author: Vojta
  10.  *
  11.  * Created on 11. listopadu 2015, 14:08
  12.  */
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16.  
  17. int isPrime(int n) {
  18.     int i, q;
  19.     if (n < 2)
  20.         return 0;
  21.     for (i = 2; 1; ++i) {
  22.         q = n / i;
  23.         if (q < i)
  24.             return 1;
  25.         if (n == q * i)
  26.             return 0;
  27.     }
  28.     return 1;
  29. }
  30.  
  31. int nextPrime(int n) {
  32.     n++;
  33.     for (; !isPrime(n); ++n)
  34.         ;
  35.     return n;
  36. }
  37.  
  38. void printFactorisationSimple(int n) {
  39.     int m = 2;
  40.     printf("%d = ", n);
  41.     while (1) {
  42.         if ( n % m == 0) {
  43.             if (n == m)
  44.                 printf("%d\n", m);
  45.             else
  46.                 printf("%d*", m);
  47.             n /= m;
  48.         } else {
  49.             m = nextPrime(m);
  50.         }
  51.         if (n == 1)
  52.             break;
  53.     }
  54. }
  55.  
  56. int getPower(int n, int d) {
  57.     int c = 0;
  58.     while (n % d == 0) {
  59.         c++;
  60.         n /= d;
  61.     }
  62.     return c;
  63. }
  64.  
  65. int ipow(int base, int exp)
  66. {
  67.     int result = 1;
  68.     while (exp)
  69.     {
  70.         if (exp & 1)
  71.             result *= base;
  72.         exp >>= 1;
  73.         base *= base;
  74.     }
  75.  
  76.     return result;
  77. }
  78.  
  79. void printFactorisationAdvanced(int n) {
  80.     int m = 2, x;
  81.     printf("%d = ", n);
  82.     while (1) {
  83.         if ( n % m == 0) {
  84.             x = getPower(n,m);
  85.             if ( n == ipow(m,x))
  86.                 printf("%d^%d\n", m, x);
  87.             else
  88.                 printf("%d^%d * ", m, x);
  89.             n /= ipow(m,x);
  90.         } else {
  91.             m = nextPrime(m);
  92.         }
  93.         if (n == 1)
  94.             break;
  95.     }
  96. }
  97.  
  98.  
  99. int main(int argc, char** argv) {
  100.  
  101.     int n, i;
  102.     printf("Zadej cele kladne cislo: ");
  103.     scanf ("%d", &n);
  104.    
  105.    
  106.     printFactorisationSimple(n);
  107.     printFactorisationAdvanced(n);
  108.    
  109.     return (EXIT_SUCCESS);
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement