I am very new to 'R' and am trying to start learning it. I have written the following program to generate the prime factors of a given number. But for mysterious reasons it generates a nonsense list at the end of the day. I cannot find where or why this is happening. Please can you help.
library(gmp)
getPrimeFactors = function(n){
primeList=c()
if(isprime(n)){
primeList <- append(primeList, n)
return (primeList)
}
currentPrime <- 2
while(TRUE){
# Check if input is divisible by the current primeList
if(n %% currentPrime == 0){
cat(sprintf("the number %f is divisible by %f\n", n, currentPrime))
n = n%/%currentPrime
cat(sprintf("current prime :%f\n", currentPrime))
primeList = append(primeList,currentPrime)
currentPrime = 2
if(isprime(n)){
primeList <- append(primeList, n)
return (primeList)
}
}
else{
#cat(sprintf("the number %f is NOT divisible by %f\n", n, currentPrime))
#cat(sprintf("current prime before is: %f\n", currentPrime))
print(c("current prime before:", currentPrime))
currentPrime = nextprime(currentPrime)
#cat(sprintf("current prime after is: %f\n", currentPrime))
print(c("current prime after:", currentPrime))
}
}
}
The problem is that nextprime(currentPrime) doesn't return a base R numeric value. It returns a value with class bigz. Look at the output of cat(nextprime(2).
To fix your code change the line
currentPrime = nextprime(currentPrime)
to
currentPrime = as.numeric(nextprime(currentPrime))
Related
I am facing difficulty to figure out the time complexity of this below function. Please help to find how to solve this question?
int sumOfDigits(int n){
int sum;`
if(n < 10){
return n;
}
sum = (n % 10) + sumOfDigits(n / 10);
return sum;
}
The function considers each digit of a number n and returns the sum of them.
The number of iterations is ⌊log10(n)⌋ + 1 and depends on the number of digits of n. Therefore, T(n) = O(log n)
This is a contest problem (ACM ICPC South America 2015), it was the hardest in the problem set.
Summary: Given integers N and K, count the number of sequences a of length N consisting of integers 1 ≤ ai ≤ K, subject to the condition that for any x in that sequence there has to be a pair i, j satisfying i < j and ai = x − 1 and aj = x, i.e. the last x is preceded by x − 1 at some point.
Example: for N = 1000 and K = 100 the solution should be congruent to 265428620 modulo (109 + 7). Other examples and details can be found in the problem description.
I tried everything in my knowledge, but I need pointers to know how to do it. I even printed some lists with brute force to find the pattern, but I didn't succeed.
I'm looking for an algorithm, or formula that allows me to get to the right solution for this problem. It can be any language.
EDIT:
I solved the problem using a formula I found on the internet (someone who explained this problem). However, just because I programmed it, doesn't mean I understand it, so the question remains open. My code is here (the online judge returns Accepted):
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll mod = 1e9+7;
ll memo[5001][5001];
ll dp(int n, int k){
// K can't be greater than N
k = min(n, k);
// if N or K is 1, it means there's only one possible list
if(n <= 1 || k <= 1) return 1;
if(memo[n][k] != -1) return memo[n][k];
ll ans1 = (n-k) * dp(n-1, k-1);
ll ans2 = k * dp(n-1, k);
memo[n][k] = ((ans1 % mod) + (ans2 % mod)) % mod;
return memo[n][k];
}
int main(){
int n, q;
for(int i=0; i<5001; i++)
fill(memo[i], memo[i]+5001, -1);
while(scanf("%d %d", &n, &q) == 2){
for(int i=0; i<q; i++){
int k;
scanf("%d", &k);
printf("%s%lld", i==0? "" : " ", dp(n, k));
}
printf("\n");
}
return 0;
}
The most important lines are the recursive call, particularly, these lines
ll ans1 = (n-k) * dp(n-1, k-1);
ll ans2 = k * dp(n-1, k);
memo[n][k] = ((ans1 % mod) + (ans2 % mod)) % mod;
Here I show the brute force algorithm for the problem in python. It works for small numbers, but for very big numbers it takes too much time. For N=1000 and K=5 it is already infeasible (Needs more than 100 years time to calculate)(In C it should also be infeasible as C is only 100 times faster than Python). So the problem actually forces you to find a shortcut.
import itertools
def checkArr(a,K):
for i in range(2,min(K+1,max(a)+1)):
if i-1 not in a:
return False
if i not in a:
return False
if a.index(i-1)>len(a)-1-a[::-1].index(i):
return False
return True
def num_sorted(N,K):
result=0
for a in itertools.product(range(1,K+1), repeat=N):
if checkArr(a,K):
result+=1
return result
num_sorted(3,10)
It returns 6 as expected.
I would like to know the simplest way to transform a number to a truncated and rounded form.
I know many way to do it "manually" (truncate manually, put a comma then round the number after) but I think there are easier ways to do it (probably with Maths methods).
Example :
1 234 567 should become 1,2 M
1 567 890 should become 1.6 M
Something like that:
static string FormatNumber(uint n)
{
if (n < 1000)
return n.ToString();
if (n < 10000)
return String.Format("{0:#,.##}K", n - 5);
if (n < 100000)
return String.Format("{0:#,.#}K", n - 50);
if (n < 1000000)
return String.Format("{0:#,.}K", n - 500);
if (n < 10000000)
return String.Format("{0:#,,.##}M", n - 5000);
if (n < 100000000)
return String.Format("{0:#,,.#}M", n - 50000);
if (n < 1000000000)
return String.Format("{0:#,,.}M", n - 500000);
return String.Format("{0:#,,,.##}B", n - 5000000);
}
Will give you this output:
1249 1.24K
12499 12.4K
124999 124K
1249999 1.24M
12499999 12.4M
124999999 124M
1249999999 1.24B
I don't think there are built-in libraries to do this.
The integer part of the base-10 logarithm gives you the exponent as appearing in the scientific notation.
If you want s significant digits, normalize by dividing by ten to the exponent, rescale by ten to s-1 and round.
e= floor(log10(x)); // => e = 6
x= Round(x * pow(10, s - 1 - e)); // => x = 12, x = 16
what is the fastest method to calculate this, i saw some people using matrices and when i searched on the internet, they talked about eigen values and eigen vectors (no idea about this stuff)...there was a question which reduced to a recursive equation
f(n) = (2*f(n-1)) + 2 , and f(1) = 1,
n could be upto 10^9....
i already tried using DP, storing upto 1000000 values and using the common fast exponentiation method, it all timed out
im generally weak in these modulo questions, which require computing large values
f(n) = (2*f(n-1)) + 2 with f(1)=1
is equivalent to
(f(n)+2) = 2 * (f(n-1)+2)
= ...
= 2^(n-1) * (f(1)+2) = 3 * 2^(n-1)
so that finally
f(n) = 3 * 2^(n-1) - 2
where you can then apply fast modular power methods.
Modular exponentiation by the square-and-multiply method:
function powerMod(b, e, m)
x := 1
while e > 0
if e%2 == 1
x, e := (x*b)%m, e-1
else b, e := (b*b)%m, e//2
return x
C code for calculating 2^n
const int mod = 1e9+7;
//Here base is assumed to be 2
int cal_pow(int x){
int res;
if (x == 0) res=1;
else if (x == 1) res=2;
else {
res = cal_pow(x/2);
if (x % 2 == 0)
res = (res * res) % mod;
else
res = (((res*res) % mod) * 2) % mod;
}
return res;
}
I need to subtract two very large integers along with modulus of 1000000007
x and y are integers 1 <= x,y <= 1000
long long s[x+1];
long long c[x+1];
for(int i=1;i<=x;i++)
c[i] = power(y,i)%mod;
s[1]=1;
for(int i=2;i<=x;i++){
sum=0;
for(int j=1;j<i;j++){
sum = (sum + (s[j]*c[i-j]%mod))%mod;
}
s[i] = (c[i] - sum)%mod; // <----------- s[i] is -ve
}
The issue is when c[i]%mod is less than Sum%mod
Eg: When c[i] is greater than Sum.
But c[i]%mod is less than Sum%mod
437001927 - 952742480
You could just add an if statement.
if(s[i]<0)
s[i] += mod
I would use
s[i] = (c[i] - sum + mod) % mod;
in this case. sum is computed modulo mod, so it can't be greater than mod.