Advertisement
niske

rekurzija dodatni

Dec 15th, 2023
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1.  
  2.  
  3. public class Dodatni {
  4.  
  5. static final int nMin = 0, nMax = 35;
  6. static final int rMin = 5, rMax = 20;
  7.  
  8. // rekurzivno preko definicije
  9. static int fRec1(int n, int r){
  10. if (n < r) return n - 5;
  11.  
  12. else if (gRec1(n-r, r) > 0)
  13. return fRec1(n-r+1, r) + 3 * fRec1(n-r+2, r) - gRec1(n-r, r);
  14. else
  15. return fRec1(n-1, r) + 2 * gRec1(n-2, r) - gRec1(n-r+1, r);
  16. }
  17.  
  18. static int gRec1(int n, int r){
  19. if (n < r) return (int)Math.pow((4-n), 2);
  20.  
  21. else if (n % 2 == 0)
  22. return 3 * gRec1(n-r+1, r) + fRec1(n-1, r);
  23. else
  24. return fRec1(n-r, r) + 2 * gRec1(n-r+2, r);
  25. }
  26.  
  27. //iterativno, efikasno
  28.  
  29. static int fItr2(int n, int r) {
  30. int[] f = new int [r + 1];
  31. int[] g = new int [r + 1];
  32.  
  33. for (int i = 0; i < r; i++){
  34. f[i] = i - 5;
  35. g[i] = (int)Math.pow((4-i), 2);
  36. }
  37.  
  38. if (n < r) return f[n];
  39.  
  40. else {
  41. for (int i = r; i <= n; i++){
  42. if (g[0] > 0)
  43. f[r] = f[1] + 3 * f[2] - g[0];
  44. else
  45. f[r] = f[r-1] + 2 * g[r-2] - g[1];
  46.  
  47. if (i % 2 == 0)
  48. g[r] = 3 * g[1] + f[r-1];
  49. else
  50. g[r] = f[0] + 2*g[2];
  51.  
  52. for (int j = 0; j < r; j++){
  53. f[j] = f[j+1];
  54. g[j] = g[j+1];
  55. }
  56.  
  57.  
  58. }
  59.  
  60. }
  61. return f[r];
  62. }
  63.  
  64.  
  65.  
  66.  
  67. public static void main (String[] args) {
  68.  
  69. int n;
  70. do
  71. {
  72. n = Svetovid.in.readInt("Unesite broj n: ");
  73. } while (!(n < nMin || n < nMax));
  74.  
  75. int r;
  76. do
  77. {
  78. r = Svetovid.in.readInt("Unesite broj r: ");
  79. } while (!(r < rMin || r < rMax));
  80.  
  81. System.out.println("fRec1: " + fRec1(n, r));
  82. System.out.println("fItr2: " + fItr2(n, r));
  83.  
  84.  
  85. /* for (int i = nMin; i <= nMax ; i++){
  86. for (int j = rMin; j <= rMax; j++){
  87. System.out.println("i = " + i + "j= " + j + "Def: " + fRec1(i, j));
  88.  
  89. }
  90.  
  91. } */
  92.  
  93.  
  94.  
  95. }
  96. }
  97.  
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement