0

In the code below, why am I not able to print the elements of vector? Not even their size. Can you please explain the reason?

#include<bits/stdc++.h>
using namespace std;
int main(){
    int n,k=2;
    cin>>n;
    vector< int >v;
    while(n!=0){
        if((n%k==0)&&(k<10)){
            n=n/k;
            v.push_back(k);
        }
        else if((n%k!=0)&&(k<10)){
            k++;
        }
    }
    cout<<v.size()<<"\n";
    for(int i=0;i<v.size();i++){
        cout<<v[i]<<" ";
    }
}
Abcd Efg
  • 2,146
  • 23
  • 41
UJM
  • 167
  • 8
  • For example, `n` won't be updated inside the loop when `n = 11` and the loop will run infinitely. – MikeCAT Jul 19 '20 at 09:39
  • [Ok, the size is printed](https://wandbox.org/permlink/pameJWbbGv4YYgBY) for `n = 0`. – MikeCAT Jul 19 '20 at 09:41
  • 1
    Please describe your desired behavior if you want us to fix your code. – MikeCAT Jul 19 '20 at 09:41
  • Even with positive `n` input smaller than 10, `n=n/k;` won't make `n` to `0` due to the `n%k==0` condition. – MikeCAT Jul 19 '20 at 09:43
  • @MikeCAT, what if n=64? Vector should have 6 elements with size of 6. Please clarify. – UJM Jul 19 '20 at 09:44
  • The vector had 6 elements after converge, but their size should be 4 (implementation-defined) and their values are all 2. [https://wandbox.org/permlink/TKQctRi0lYpe3fa5](https://wandbox.org/permlink/TKQctRi0lYpe3fa5) – MikeCAT Jul 19 '20 at 09:48
  • 2
    Please read: [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). tl;dr; Replace it with the correct header files so that everyone can compile your program. – Ted Lyngmo Jul 19 '20 at 09:49
  • @MikeCAT thanks, I got it what you are saying. that n will never gonna be zero and so loop will run infinitely .I will just replace (n!=0) with (n!=1) in while loop. – UJM Jul 19 '20 at 10:03
  • Changing `(n!=0)` to `(n!=1)` won't solve the issue in `n = 11` case. Is it guaranteed that such case won't be inputted or just you are going to think about it later? – MikeCAT Jul 19 '20 at 10:05
  • @MikeCAT for prime numbers I still have to make another block! – UJM Jul 19 '20 at 10:10
  • Then how about `n = 143`, which is not a prime number? – MikeCAT Jul 19 '20 at 10:14
  • @MikeCAT limit of n is from 1 to 100; – UJM Jul 19 '20 at 10:28
  • 1
    Then how about `n = 91`? – MikeCAT Jul 19 '20 at 10:30
  • @MikeCAT that's why there is no supernatural number for 91 and that's what I am trying to find out. – UJM Jul 19 '20 at 10:47

0 Answers0